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

class Awards extends CI_Controller 
{
    public function __construct() 
    {
        parent::__construct();   
        $this->load->library('session');
        $allowed_methods = ['api_awards'];
        if (!in_array($this->router->fetch_method(), $allowed_methods) && $this->session->userdata('validated') != true)
        {
            redirect('login');
        }     
        $this->load->helper('url');
        $this->load->model('Awards_Achievements_Model');
        $this->load->model('Awards_Achievements_Model','awards');  
    }

    public function api_awards()
    {
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json");

        $query = $this->db
            ->where('status', '1')
            ->where('publish', '1')
            ->order_by('add_date', 'ASC')
            ->get(TBL_AWARDS);

        $data = [];
        foreach ($query->result() as $row) {
            $data[] = [
                'id' => $row->id,
                'title' => $row->title,
                'description' => $row->description,
                'person_img_url' => !empty($row->person_img) 
                    ? base_url("../assets/images/awards/".$row->person_img) 
                    : base_url("assets/images/default-user.png"),
                'award_img_url' => !empty($row->award_img) 
                    ? base_url("../assets/images/awards/".$row->award_img) 
                    : "",
            ];
        }

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

    public function index() 
    {
        $this->load->helper('url');        
        $data["extra_js"] = array("awards");
        $data['controller'] = base_url('awards');
        $data['page_title'] = "Manage Awards & Achievements | CMS - Vinayak Webtech +91 90336 22526";
        $data['page_heading'] = "Manage Awards & Achievements";
        $data['main_content'] = 'awards';
        $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');
        $person_photo = "";
        $award_photo = "";
      
        
        $this->upload->initialize($this->set_upload_options()); 
        if($this->upload->do_upload('person_file'))
        { 
            $person_Data = $this->upload->data(); 
            $person_photo = $person_Data['file_name'];
        }
        else
        { 
            $error = $this->upload->display_errors();
            if(!empty($_FILES['person_file']['name'])) {
                $response = array("status" => "error", "heading" => "Upload Error", "message" => "Person Image: " . $error);
                echo json_encode($response);
                die;
            }
        }
  
        $this->upload->initialize($this->set_upload_options()); 
        if($this->upload->do_upload('award_file'))
        { 
            $award_Data = $this->upload->data(); 
            $award_photo = $award_Data['file_name'];
        }
        else
        { 
            $error = $this->upload->display_errors();
            if(!empty($_FILES['award_file']['name'])) {
                $response = array("status" => "error", "heading" => "Upload Error", "message" => "Award Image: " . $error);
                echo json_encode($response);
                die;
            }
        }
        
        $get_old_person_doc = $this->input->post('get_old_person_doc'); 
        $get_old_award_doc = $this->input->post('get_old_award_doc'); 
   
        
        if(!empty($person_photo) && empty($get_id))
        {
            $person_img_path = $person_photo;
        } 
        else if(empty($person_photo) && $get_id > 0)
        { 
            $person_img_path = $get_old_person_doc;
        }
        else if(!empty($person_photo) && $get_id > 0)
        {
            if(!empty($get_old_person_doc) && file_exists(AWARD_PATH."/".$get_old_person_doc))
            {
                unlink(AWARD_PATH."/".$get_old_person_doc);
            }
            $person_img_path = $person_photo;
        }        
        else
        {
            $person_img_path = $person_photo;
        }
 
       
        if(!empty($award_photo) && empty($get_id))
        {
            $award_img_path = $award_photo;
        } 
        else if(empty($award_photo) && $get_id > 0)
        { 
            $award_img_path = $get_old_award_doc;
        }
        else if(!empty($award_photo) && $get_id > 0)
        {
            if(!empty($get_old_award_doc) && file_exists(AWARD_PATH."/".$get_old_award_doc))
            {
                unlink(AWARD_PATH."/".$get_old_award_doc);
            }
            $award_img_path = $award_photo;
        }        
        else
        {
            $award_img_path = $award_photo;
        }

        if($get_id > 0)
        { 
            $data = array(
                'title' => $this->input->post('title'),  
                'description' => $this->input->post('description'),
                'update_date' => date("Y-m-d H:i:s"),  
            );
             
            if(!empty($person_img_path)) {
                $data['person_img'] = $person_img_path;
            }

            if(!empty($award_img_path)) {
                $data['award_img'] = $award_img_path;
            }
            
            $this->awards->update(array('id' => $get_id), $data); 
            $response = array("status" => "ok", "heading" => "Updated", "message" => "Award & Achievement Updated Successfully.");
        }
        else
        {
            $data = array(
                'title' => $this->input->post('title'), 
                'description' => $this->input->post('description'),
                'person_img' => $person_img_path,
                'award_img' => $award_img_path,
                'add_date' => date("Y-m-d H:i:s"),
            );
            $insert = $this->awards->save($data);  

            $response = array("status" => "ok", "heading" => "Added", "message" => "Award & Achievement Added Successfully.");
        }
         
        echo json_encode($response);
        die;        
    }

    private function set_upload_options()
    {   
        $config = array();
        $config['upload_path'] = AWARD_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()
    { 
        $list = $this->awards->get_datatables();
        $data = array();
        $no = $_POST['start'] + 1;
        foreach ($list as $award) {
            $row = array();
            $row[] = $no++; 
            $row[] = $award->title;
            
            $row[] = '<div class="award-desc" title="'.htmlspecialchars(strip_tags($award->description)).'">'.strip_tags($award->description).'</div>';
 
            if (!empty($award->person_img)) {
                $person_img_path = AWARD_PATH . '/' . $award->person_img;
                if (file_exists($person_img_path)) {
                    $person_img_url = base_url('../assets/images/awards/' . $award->person_img);
                    $row[] = '<img src="'.$person_img_url.'" style="height:50px;width:auto;">';
                } else {
                    $row[] = '<span>-</span>';
                }
            } else {
                $row[] = '<span class="text-muted">No Image</span>';
            }

            if (!empty($award->award_img)) {
                $award_img_path = AWARD_PATH . '/' . $award->award_img;
                if (file_exists($award_img_path)) {
                    $award_img_url = base_url('../assets/images/awards/' . $award->award_img);
                    $row[] = '<img src="'.$award_img_url.'" style="height:50px;width:auto;">';
                } else {
                    $row[] = '<span>-</span>';
                }
            } else {
                $row[] = '<span class="text-muted">No Image</span>';
            }

            $row[] = date("d-m-Y g:i A", strtotime($award->add_date));
            
            if($award->status == '1')
                $row[] = '<a class="label orange-bg active-btn" href="javascript:void(0)" title="Active" onclick="deactive('."'".$award->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('."'".$award->id."'".')"><span class="badge badge-danger">Deactive</span></a>';

            $row[] = '<a type="button" href="javascript:void(0);" onclick="edit_data('."'".$award->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="'.$award->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" => $_POST['draw'],
            "recordsTotal" => $this->awards->count_all(),
            "recordsFiltered" => $this->awards->count_filtered(),
            "data" => $data,
        ); 
        echo json_encode($output);
    }

    public function edit($id)
    {
        $row = $this->awards->get_by_id($id);

        $data = array(
            'id' => $row->id,
            'title' => $row->title,
            'description' => $row->description,
            'person_img' => $row->person_img,
            'award_img' => $row->award_img
        );

        echo json_encode($data);
    }

    public function active($id)
    {
        $data = array();
        $sql = "update ". TBL_AWARDS ." set status='1' where id ='".$id."'";       
        $res = $this->db->query($sql);
        $data[] = "sucess";
        die(json_encode($data));
    }

    public function deactive($id)
    {
        $data = array();
        $sql = "update ". TBL_AWARDS ." set status='0' where id ='".$id."'";       
        $res = $this->db->query($sql);
        $data[] = "sucess";
        die(json_encode($data));
    }

    public function delete($id)
    {
        $get_id = $id; 
        $sql_query = $this->db->query("select id, person_img, award_img, publish from ". TBL_AWARDS ." where id='$get_id' and publish='1'")->row(); 
        if (isset($sql_query))
        {   
            if(!empty($sql_query->person_img))
            {
                $person_img_file_path = AWARD_PATH . "/" . $sql_query->person_img; 
                if(file_exists($person_img_file_path)) {
                    unlink($person_img_file_path);
                }
            }

            if(!empty($sql_query->award_img))
            {
                $award_img_file_path = AWARD_PATH . "/" . $sql_query->award_img; 
                if(file_exists($award_img_file_path)) {
                    unlink($award_img_file_path);
                }
            }
        }
        $response = array("status" => "ok", "heading" => "Deleted", "message" => "Award & Achievement Deleted Successfully.", "tbc_name" => "");
        $this->awards->delete_by_id($get_id);  
        echo json_encode($response);  
        die;
    }
}