<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Newsevents extends CI_Controller 
{
    public function __construct() 
    {
        parent::__construct();   
        $this->load->library('session');
        $allowed_methods = ['api_news_events'];
        if (!in_array($this->router->fetch_method(), $allowed_methods) && $this->session->userdata('validated') != true)
        {
            redirect('login');
        }     
        $this->load->helper('url');
        $this->load->model('News_Event_Model');
        $this->load->model('News_Event_Model','category');  
    }
    
    public function api_news_events()
    {
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json");

        $query = $this->db
            ->where('status', '1')
            ->where('publish', '1')
            ->order_by('date', 'DESC')
            ->order_by('time', 'DESC')
            ->get(TBL_NEWS_EVENT);

        $data = [];

        foreach ($query->result() as $row) {
            $data[] = [
                "id" => $row->id,
                "news_event_title" => $row->news_event_title,
                "news_event_description" => $row->news_event_description,
                "date" => date("Y-m-d", strtotime($row->date)),
                "day" => date("d", strtotime($row->date)),
                "month" => date("M", strtotime($row->date)),
                "year" => date("Y", strtotime($row->date)),
                "time" => $row->time,
                "image_url" => base_url("../assets/images/news-event/" . $row->news_event_image),
            ];
        }
 
        $grouped = [];
        foreach ($data as $event) {
            $year = $event['year'];
            if (!isset($grouped[$year])) {
                $grouped[$year] = [];
            }
            $grouped[$year][] = $event;
        }

        echo json_encode([
            "status" => "success",
            "data" => $grouped
        ]);
        exit;
    }

    public function index() 
    {
        $this->load->helper('url');        
        $data["extra_js"] = array("newsevents");
        $data['controller'] = base_url('newsevents/add');
        $data['page_title'] = "Manage News & Events | CMS";
        $data['page_heading'] = "Manage News & Events";
        $data['main_content'] = 'newsevents';
        $this->load->view('main_content', $data); 
    }  

    public function submit()
    {
        date_default_timezone_set('Asia/Calcutta'); 
        $get_id = $this->input->post('id'); 
            
        $this->load->library('upload');
        $photo = "";      
        $this->upload->initialize($this->set_upload_options()); 
        
        if($this->upload->do_upload('file'))
        { 
            $photo_Data = $this->upload->data(); 
            $photo = $photo_Data['file_name'];
        } 
        
        $get_old_doc = $this->input->post('get_old_doc'); 

        if(!empty($photo) && empty($get_id))
        {
            $doc_path = $photo;
        } 
        else if(empty($photo) && $get_id > 0)
        { 
            $doc_path = $get_old_doc;
        }
        else if(!empty($photo) && $get_id > 0)
        {
            if(!empty($get_old_doc) && file_exists(NEWS_EVENT_PATH."/".$get_old_doc))
            {
                unlink(NEWS_EVENT_PATH."/".$get_old_doc);
            }
            $doc_path = $photo;
        }        
        else
        {
            $doc_path = $photo;
        }

        if($get_id > 0)
        { 
            $data = array(
                'news_event_title' => ucwords(strtolower($this->input->post('news_event_title'))),  
                'news_event_description' => $this->input->post('news_event_description'), 
                'date' => $this->input->post('date'),
                'time' => $this->input->post('time'),
                'news_event_image' => $doc_path,  
                'update_uid' => $this->session->userdata('user_id'),
                'update_date' => date("Y-m-d H:i:s"),  
            );
            $this->category->update(array('id' => $get_id), $data); 
            $response = array("status" => "ok", "heading" => "Update", "message" => "Data Updated Successfully.");
        }
        else
        {
            $data = array(
                'news_event_title' => ucwords(strtolower($this->input->post('news_event_title'))),  
                'news_event_description' => $this->input->post('news_event_description'), 
                'date' => $this->input->post('date'),
                'time' => $this->input->post('time'),
                'news_event_image' => $doc_path,  
                'add_uid' => $this->session->userdata('user_id'),
                'add_date' => date("Y-m-d H:i:s")
            );
            $insert = $this->category->save($data);  
            $response = array("status" => "ok", "heading" => "Add", "message" => "Data Added Successfully.");
        }
         
        echo json_encode($response);
        exit;        
    }

    private function set_upload_options()
    {   
        $config = array();
        $config['upload_path'] = NEWS_EVENT_PATH; 
        $config['allowed_types'] = 'jpeg|jpg|png';
        $config['max_width'] = 0;
        $config['max_height'] = 0;
        $config['max_size'] = '2048';
        $config['encrypt_name'] = TRUE; 
        return $config;
    }

    public function list()
    { 
        try {
            $list = $this->category->get_datatables();
            $data = array();
            $no = isset($_POST['start']) ? $_POST['start'] + 1 : 1;
            
            foreach ($list as $category) {
                $row = array();
                $row[] = $no++; 
                $row[] = $category->news_event_title;
                
                
                if(!empty($category->news_event_image))
                {
                    $img_path = base_url("../assets/images/news-event/" . $category->news_event_image);
                    if(file_exists(NEWS_EVENT_PATH . "/" . $category->news_event_image))
                    {
                        $row[] = "<img src='".$img_path."' style='width:auto; height:50px;' />"; 
                    }
                    else
                    {
                        $row[] = "<span>-</span>";
                    }
                }
                else
                {
                    $row[] = "<span class='badge badge-secondary'>No Image</span>";
                }

                $row[] = date("d-m-Y", strtotime($category->date)) ." " .date("h:i A", strtotime($category->time));
                
                if($category->status == '1')
                    $row[] = '<a class="label orange-bg active-btn" href="javascript:void(0)" title="Active" onclick="deactive('."'".$category->id."'".')"><span class="badge badge-success">Active</span></a>';   
                else
                    $row[] = '<a class="label red-bg deactive-btn" href="javascript:void(0)" title="Deactive" onclick="active('."'".$category->id."'".')"><span class="badge badge-danger">Deactive</span></a>';

                $row[] = '<a type="button" href="javascript:void(0);" onclick="edit_data('."'".$category->id."'".')" class="edit_btn btn btn-sm btn-icon" title="Edit Record"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" class="eva eva-edit-2-outline"><g data-name="Layer 2"><g data-name="edit-2"><rect width="24" height="24" opacity="0"></rect><path d="M19 20H5a1 1 0 0 0 0 2h14a1 1 0 0 0 0-2z"></path><path d="M5 18h.09l4.17-.38a2 2 0 0 0 1.21-.57l9-9a1.92 1.92 0 0 0-.07-2.71L16.66 2.6A2 2 0 0 0 14 2.53l-9 9a2 2 0 0 0-.57 1.21L4 16.91a1 1 0 0 0 .29.8A1 1 0 0 0 5 18zM15.27 4L18 6.73l-2 1.95L13.32 6zm-8.9 8.91L12 7.32l2.7 2.7-5.6 5.6-3 .28z"></path></g></g></svg></a>
                    <a type="button" class="delete_btn btn btn-sm btn-icon" href="javascript:" title="Delete Record" data-id="'.$category->id.'"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" class="eva eva-trash-2-outline"><g data-name="Layer 2"><g data-name="trash-2"><rect width="24" height="24" opacity="0"></rect><path d="M21 6h-5V4.33A2.42 2.42 0 0 0 13.5 2h-3A2.42 2.42 0 0 0 8 4.33V6H3a1 1 0 0 0 0 2h1v11a3 3 0 0 0 3 3h10a3 3 0 0 0 3-3V8h1a1 1 0 0 0 0-2zM10 4.33c0-.16.21-.33.5-.33h3c.29 0 .5.17.5.33V6h-4zM18 19a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V8h12z"></path><path d="M9 17a1 1 0 0 0 1-1v-4a1 1 0 0 0-2 0v4a1 1 0 0 0 1 1z"></path><path d="M15 17a1 1 0 0 0 1-1v-4a1 1 0 0 0-2 0v4a1 1 0 0 0 1 1z"></path></g></g></svg></a>';
                
                $data[] = $row;
            }
            
            $output = array(
                "draw" => isset($_POST['draw']) ? intval($_POST['draw']) : 1,
                "recordsTotal" => $this->category->count_all(),
                "recordsFiltered" => $this->category->count_filtered(),
                "data" => $data,
            );
            
            header('Content-Type: application/json');
            echo json_encode($output);
            exit;
            
        } catch (Exception $e) {
            header('Content-Type: application/json');
            echo json_encode([
                "draw" => isset($_POST['draw']) ? intval($_POST['draw']) : 1,
                "recordsTotal" => 0,
                "recordsFiltered" => 0,
                "data" => [],
                "error" => $e->getMessage()
            ]);
            exit;
        }
    }

    public function edit($id)
    {
        header('Content-Type: application/json');
        
        try {
            $s_data = $this->category->get_by_id($id);
            
            if($s_data) {
                
                $data = array(
                    'id' => $s_data->id,
                    'title' => $s_data->news_event_title,  
                    'description' => $s_data->news_event_description,  
                    'date' => $s_data->date,
                    'time' => $s_data->time,
                    'image' => $s_data->news_event_image   
                );
                echo json_encode($data);
            } else {
                echo json_encode(['error' => 'Record not found']);
            }
        } catch (Exception $e) {
            echo json_encode(['error' => $e->getMessage()]);
        }
        exit;
    }

    public function active($id)
    {
        header('Content-Type: application/json');
        
        try {
            $this->db->where('id', $id);
            $this->db->update(TBL_NEWS_EVENT, array('status' => '1'));
            echo json_encode('sucess');  
        } catch (Exception $e) {
            echo json_encode(['error' => $e->getMessage()]);
        }
        exit;
    }

    public function deactive($id)
    {
        header('Content-Type: application/json');
        
        try {
            $this->db->where('id', $id);
            $this->db->update(TBL_NEWS_EVENT, array('status' => '0'));
            echo json_encode('sucess');   
        } catch (Exception $e) {
            echo json_encode(['error' => $e->getMessage()]);
        }
        exit;
    }

    public function delete($id)
    {
        header('Content-Type: application/json');
        
        try {
            $get_id = $id; 
            $sql_query = $this->db->query("SELECT id, news_event_image, publish FROM ". TBL_NEWS_EVENT ." WHERE id='$get_id' AND publish='1'")->row(); 
            
            if (isset($sql_query))
            {   
                $news_event_image = $sql_query->news_event_image;
                if(!empty($sql_query->news_event_image))
                {
                    $image_file_path = NEWS_EVENT_PATH . "/" . $news_event_image; 
                    if(file_exists($image_file_path))
                    {
                        unlink($image_file_path);
                    }
                }
            }
            
            $this->category->delete_by_id($get_id);
            
            $response = array(
                "status" => "ok", 
                "heading" => "Deleted", 
                "message" => "Record Deleted Successfully.", 
                "tbc_name" => ""
            );
            
            echo json_encode($response);
            
        } catch (Exception $e) {
            echo json_encode([
                "status" => "error",
                "message" => $e->getMessage()
            ]);
        }
        exit;
    }
}