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

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

    public function index() 
    {
        $this->load->helper('url');        
        $data["extra_js"] = array("video-gallery");
        $data['controller'] = base_url('videogallery');
        $data['page_title'] = "Manage Video Gallery | CMS - Vinayak Webtech +91 90336 22526";
        $data['page_heading'] = "Manage Video Gallery";
        $data['main_content'] = 'videogallery';
        $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 = "";      
         
        if(!empty($_FILES['file']['name']))
        {
            $this->upload->initialize($this->set_upload_options()); 
            if($this->upload->do_upload('file'))
            { 
                $photo_Data = $this->upload->data(); 
                $photo = $photo_Data['file_name'];
            }
            else
            { 
                $error = $this->upload->display_errors();
                $response = array("status" => "error", "heading" => "Upload Error", "message" => strip_tags($error));
                echo json_encode($response);
                die;
            }
        }
        
        $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(VIDEO_GALLERY_PATH."/".$get_old_doc))
            {
                @unlink(VIDEO_GALLERY_PATH."/".$get_old_doc);
            }
            $doc_path = $photo;
        }        
        else
        {
            $doc_path = $photo;
        }

      
        $doctor_cat_id = '';
        $doctor_id = $this->input->post('doctor_id');
        if(!empty($doctor_id)) {
            $doctor_info = $this->db->select('doc_cat_id')->where('id', $doctor_id)->get('doc_profile')->row();
            if($doctor_info) {
                $doctor_cat_id = $doctor_info->doc_cat_id;
            }
        }

        if($get_id > 0)
        { 
          
            $data = array(
                'video_cat_id' => $this->input->post('video_cat_id'),
                'doctor_id' => $doctor_id,
                'doctor_cat_id' => $doctor_cat_id,  
                'title' => ucwords(strtolower($this->input->post('title'))),  
                'video_url' => $this->input->post('video_url'),
                'sequence_no' => $this->input->post('sequence_no'), 
            );
             
            if(!empty($doc_path)) {
                $data['image'] = $doc_path;
            }
            
            $update_result = $this->video_gallery->update(array('id' => $get_id), $data); 
            
            $response = array("status" => "ok", "heading" => "Updated", "message" => "Data Updated Successfully.");
        }
        else
        {
            // ADD NEW
            if(empty($doc_path)) {
                $response = array("status" => "error", "heading" => "Error", "message" => "Please upload thumbnail image!");
                echo json_encode($response);
                die;
            }
            
            $data = array(
                'video_cat_id' => $this->input->post('video_cat_id'),
                'doctor_id' => $doctor_id,
                'doctor_cat_id' => $doctor_cat_id, 
                'title' => ucwords(strtolower($this->input->post('title'))),  
                'video_url' => $this->input->post('video_url'),
                'sequence_no' => $this->input->post('sequence_no'), 
                'image' => $doc_path,  
                'add_date' => date("Y-m-d H:i:s"),
                'date' => date("Y-m-d"),
                'time' => date("H:i:s"), 
            );
            
            $insert = $this->video_gallery->save($data);  

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

    private function set_upload_options()
    {   
       
        if (!is_dir(VIDEO_GALLERY_PATH)) {
            mkdir(VIDEO_GALLERY_PATH, 0777, true);
        }
        
        $config = array();
        $config['upload_path'] = VIDEO_GALLERY_PATH; 
        $config['allowed_types'] = 'jpeg|jpg|png';
        $config['max_width'] = 0;
        $config['max_height'] = 0;
        $config['max_size'] = '1024';  
        $config['encrypt_name'] = TRUE; 
        return $config;
    }

    public function gallery_list()
    { 
        $list = $this->video_gallery->get_datatables();
        $data = array();
        $no = $_POST['start'] + 1;
        
        foreach ($list as $video) {
            $row = array();
            $row[] = $no++; 
            $row[] = !empty($video->cat_name) ? $video->cat_name : '<span class="text-muted">N/A</span>';
 
            $row[] = $video->title;
            $row[] = $video->sequence_no; 

      
            $img_url = base_url() . 'assets/images/videogallery/' . $video->image;
            $row[] = "<img src='".$img_url."' style='width:auto; height:50px;' />"; 

            $row[] = date("d-m-Y g:i A", strtotime($video->add_date));
            
            $url_html = '';
            if(!empty($video->video_url)) {
                $url_html = '<a href="'.$video->video_url.'" target="_blank" class="badge badge-info" title="Video URL"><i class="mdi mdi-youtube"></i> Video</a>';
            } else {
                $url_html = '<span class="text-muted">No URL</span>';
            }
            $row[] = $url_html;
            
            if($video->status == '1')
                $row[] = '<a class="label orange-bg active-btn" href="javascript:void(0)" title="Active" onclick="deactive('."'".$video->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('."'".$video->id."'".')"><span class="badge badge-danger">Deactive</span></a>';

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

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

        if($row) {
            $data = array(
                'id' => $row->id,
                'video_cat_id' => $row->video_cat_id,
                'doctor_id' => $row->doctor_id ?? '',
                'title' => $row->title,
                'image' => $row->image,
                'video_url' => $row->video_url,
                'sequence_no' => $row->sequence_no
            );
            echo json_encode($data);
        } else {
            echo json_encode(array('error' => 'Record not found'));
        }
    }

    public function active($id)
    {
        $data = array();
        $this->db->where('id', $id);
        $this->db->update(TBL_VIDEO_GALLERY, array('status' => '1'));
        $data[] = "sucess";
        die(json_encode($data));
    }

    public function deactive($id)
    {
        $data = array();
        $this->db->where('id', $id);
        $this->db->update(TBL_VIDEO_GALLERY, array('status' => '0'));
        $data[] = "sucess";
        die(json_encode($data));
    }

    public function delete($id)
    {
        $get_id = $id; 
        $sql_query = $this->db->query("select id, image, publish from ". TBL_VIDEO_GALLERY ." where id='$get_id' and publish='1'")->row(); 
        
        if (isset($sql_query))
        {   
            $image = $sql_query->image;
            if(!empty($image))
            {
                $image_file_path = VIDEO_GALLERY_PATH . "/" . $image; 
                if(file_exists($image_file_path)) {
                    @unlink($image_file_path);
                }
            }
        }
        
        $response = array("status" => "ok", "heading" => "Deleted", "message" => "Record Delete Successfully.", "tbc_name" => "");
        $this->video_gallery->delete_by_id($get_id);  
        echo json_encode($response);  
        die;
    }

    public function get_categories()
    {
        $categories = $this->video_gallery->get_video_cat_list();
        echo json_encode($categories);
    }

  
    public function get_doctors()
    {
        $doctors = $this->video_gallery->get_doctors_list();
        echo json_encode($doctors);
    }
 
    
    public function api_video_gallery()
    {
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json");

        $query = $this->db
            ->select('vg.*, vc.cat_name, d.doc_name')
            ->from(TBL_VIDEO_GALLERY . ' vg')
            ->join('video_category vc', 'vc.id = vg.video_cat_id', 'LEFT')
            ->join('doc_profile d', 'd.id = vg.doctor_id', 'LEFT')
            ->where('vg.status', '1')
            ->where('vg.publish', '1')
            ->order_by('vg.sequence_no', 'ASC')
            ->get();

        $data = [];
        foreach ($query->result() as $row) {
            $thumbnail_url = base_url() . 'assets/images/videogallery/' . $row->image; 
            
            $data[] = [
                "id" => $row->id,
                "title" => $row->title,
                "video_url" => $row->video_url,
                "thumb_url" => $thumbnail_url,
                "thumbnail_url" => $thumbnail_url,
                "category" => $row->cat_name,
                "doctor_name" => $row->doc_name,
                "doctor_id" => !empty($row->doctor_id) ? (int)$row->doctor_id : null, // ADDED: Include doctor_id
                "sequence_no" => $row->sequence_no
            ];
        }

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

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

        $query = $this->db
            ->select('id, cat_name')
            ->from('video_category')
            ->where('status', '1')
            ->where('publish', '1')
            ->order_by('cat_name', 'ASC')
            ->get();

        $data = [];
        foreach ($query->result() as $row) {
            $data[] = [
                "id" => $row->id,
                "cat_name" => $row->cat_name
            ];
        }

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