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

class Doctor extends CI_Controller 
{
    public function __construct() 
    {
        parent::__construct();   
        $this->load->library('session');
        $allowed_methods = ['api_home_doctors','api_doctors','api_doctor_detail','get_specialities'];
        if (!in_array($this->router->fetch_method(), $allowed_methods) && $this->session->userdata('validated') != true)
        {
            redirect('login');
        }     
        $this->load->helper('url');
        $this->load->model('Doctor_Profile_Model');
        $this->load->model('Doctor_Profile_Model','doctor');  
    }
    
    public function api_home_doctors()
    {
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json");
    
        $this->db->select('
            d.id,
            d.doc_name,
            d.qualification,
            d.doc_cat_sub,
            d.doc_cat_id,
            d.image,
            d.sequence_no
        ');
        $this->db->from(TBL_DOCTOR_PROFILE . ' d');
        $this->db->where('d.status', '1');
        $this->db->order_by('d.sequence_no', 'ASC');
    
        $query = $this->db->get();
    
        $doctors_data = [];
    
        foreach ($query->result() as $row) 
        {
        // Get all specialties for this doctor 
            $doctors_data[] = [
                "id" => $row->id,
                "name" => $row->doc_name,
                "qualification" => $row->qualification,
                "specialty" => $row->doc_cat_sub,
                 
                "image_url" => base_url("../assets/images/doctors/" . $row->image),
                "sequence" => $row->sequence_no,
            ];
        }
    
        echo json_encode([
            "status" => "success",
            "data" => $doctors_data
        ]);
        exit;
    }
  
   public function api_doctors()
{
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json");

    $this->db->select('
        d.id,
        d.doc_name,
        d.qualification,
        d.doc_cat_sub,
        d.doc_cat_id,
        d.image,
        d.sequence_no
    ');
    $this->db->from(TBL_DOCTOR_PROFILE . ' d');
    $this->db->where('d.status', '1');
    $this->db->order_by('d.sequence_no', 'ASC');

    $query = $this->db->get();

    $doctors_data = [];

    foreach ($query->result() as $row) {
        // Get all specialties for this doctor
        $specialty_ids = !empty($row->doc_cat_id) ? explode(',', $row->doc_cat_id) : [];
        
        foreach ($specialty_ids as $specialty_id) {
            $specialty_id = trim($specialty_id);
            
            // Get specialty name
            $specialty = $this->db->get_where(TBL_SPECIALIY, array('id' => $specialty_id))->row();
            $specialty_name = $specialty ? $specialty->cat_name : 'Others';
            
            // Create entry for this doctor-specialty combination
            $doctors_data[] = [
                "id" => $row->id,
                "name" => $row->doc_name,
                "qualification" => $row->qualification,
                "specialty" => $row->doc_cat_sub,
                "category" => $specialty_name,    
                "category_id" => $specialty_id,  
                "image_url" => base_url("../assets/images/doctors/" . $row->image),
                "sequence" => $row->sequence_no
            ];
        }
        
        // If no specialties, still add the doctor
        if (empty($specialty_ids)) {
            $doctors_data[] = [
                "id" => $row->id,
                "name" => $row->doc_name,
                "qualification" => $row->qualification,
                "specialty" => $row->doc_cat_sub,
                "category" => "Others",    
                "category_id" => null,  
                "image_url" => base_url("../assets/images/doctors/" . $row->image),
                "sequence" => $row->sequence_no
            ];
        }
    }

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


    public function get_specialities() 
    {
        $this->db->select("id, cat_name");
        $this->db->from(TBL_SPECIALIY);
        $this->db->where('publish', '1');
        $this->db->where('status', '1');
        $this->db->order_by('sequence_no', 'ASC');
        $query = $this->db->get();
        
        $data = array();
        if($query->num_rows() > 0) {
            foreach($query->result() as $cat) {
                $data[] = array(
                    'id' => $cat->id,
                    'cat_name' => $cat->cat_name
                );
            }
        }
        
        header('Content-Type: application/json');
        echo json_encode($data);
    }

public function api_doctor_detail($id = null)
{
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json");

    $query = $this->db
        ->where('id', $id)
        ->where('status', '1')
        ->get(TBL_DOCTOR_PROFILE);

    if ($query->num_rows() > 0) {
        $row = $query->row();
        
        // Get category names
        $category_names = array();
        if(!empty($row->doc_cat_id)) {
            $category_ids = explode(',', $row->doc_cat_id);
            foreach($category_ids as $cat_id) {
                $cat = $this->db->get_where(TBL_SPECIALIY, array('id' => trim($cat_id)))->row();
                if($cat) {
                    $category_names[] = $cat->cat_name;
                }
            }
        }
        
        $opd_images = [];
        $opd_query = $this->db
            ->where('doctor_id', $id)
            ->where('status', '1')
            ->order_by('sequence_no', 'ASC')
            ->get('opd_img_gallery');    
        
        if ($opd_query->num_rows() > 0) {
            foreach ($opd_query->result() as $opd_row) {
                $opd_images[] = [
                    'id' => $opd_row->id,
                    'title' => isset($opd_row->title) ? $opd_row->title : '',
                    'image_url' => !empty($opd_row->image) 
                        ? base_url("../assets/images/peripheral/" . $opd_row->image) 
                        : null
                ];
            }
        }
        
        $data = [
            'id' => $row->id,
            'name' => $row->doc_name,
            'specialty' => $row->doc_cat_sub,
            'category' => implode(', ', $category_names),
            'category_id' => $row->doc_cat_id,
            'qualification' => $row->qualification,
            'description' => $row->description,
            'special_interest' => $row->special_interest,
            'consulting_days1' => $row->consulting_days1,
            'consulting_days2' => $row->consulting_days2,
            'image_url' => !empty($row->image) 
                ? base_url("../assets/images/doctors/" . $row->image) 
                : base_url("../assets/images/doctors/default-image.JPG"),
            'upcoming_opds_image_url' => !empty($row->upcoming_opds_image) 
                ? base_url("../assets/images/doctors/" . $row->upcoming_opds_image) 
                : null,
            'meta_title' => $row->meta_title,
            'meta_description' => $row->meta_description,
            'meta_keywords' => $row->meta_keywords,
            'opd_images' => $opd_images 
        ];

        echo json_encode([
            "status" => "success",
            "data" => $data
        ]);
    } else {
        echo json_encode([
            "status" => "error",
            "message" => "Doctor not found"
        ]);
    }
    exit;
}

    public function index() 
    {
        $this->load->helper('url');        
        $data["extra_js"] = array("doctor");
        $data['controller'] = base_url('doctor');
        $data['page_title'] = "Manage Doctors | CMS - Vinayak Webtech +91 90336 22526";
        $data['page_heading'] = "Manage Doctors";
        $data['main_content'] = 'doctor';
        $this->load->view('main_content', $data); 
    }  

  public function submit()
{
    date_default_timezone_set('Asia/Calcutta'); 
    $get_id = $this->input->post('id'); 
    $doc_cat_ids = $this->input->post('doc_cat_id');
    $doc_cat_ids = is_array($doc_cat_ids) ? implode(',', $doc_cat_ids) : '';

    $this->load->library('upload');
    $photo = "";      
    $opd_photo = "";
    
    $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();
        if(!empty($_FILES['file']['name'])) {
            $response = array("status" => "error", "heading" => "Upload Error", "message" => $error);
            echo json_encode($response);
            die;
        }
    }
    
    $this->upload->initialize($this->set_upload_options()); 
    if($this->upload->do_upload('opd_file'))
    { 
        $opd_photo_Data = $this->upload->data(); 
        $opd_photo = $opd_photo_Data['file_name'];
    }
    else
    { 
        $error = $this->upload->display_errors();
        if(!empty($_FILES['opd_file']['name'])) {
            $response = array("status" => "error", "heading" => "Upload Error", "message" => $error);
            echo json_encode($response);
            die;
        }
    }
    
    $get_old_doc = $this->input->post('get_old_doc'); 
    $get_old_opd_image = $this->input->post('get_old_opd_image'); 
 
    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(DOCTOR_PATH."/".$get_old_doc))
        {
            unlink(DOCTOR_PATH."/".$get_old_doc);
        }
        $doc_path = $photo;
    }        
    else
    {
        $doc_path = $photo;
    }

    if(!empty($opd_photo) && empty($get_id))
    {
        $opd_image_path = $opd_photo;
    } 
    else if(empty($opd_photo) && $get_id > 0)
    { 
        $opd_image_path = $get_old_opd_image;
    }
    else if(!empty($opd_photo) && $get_id > 0)
    {
        if(!empty($get_old_opd_image) && file_exists(DOCTOR_PATH."/".$get_old_opd_image))
        {
            unlink(DOCTOR_PATH."/".$get_old_opd_image);
        }
        $opd_image_path = $opd_photo;
    }        
    else
    {
        $opd_image_path = $opd_photo;
    }

    if($get_id > 0)
    { 
        $data = array(
            'doc_cat_id' => $doc_cat_ids,
            'doc_cat_sub' => $this->input->post('doc_cat_sub'),
            'doc_name' => $this->input->post('doc_name'),
            'qualification' => $this->input->post('qualification'),
            'contact_no' => $this->input->post('contact_no'),
            'email' => $this->input->post('email'),
            'description' => $this->input->post('description'),
            'special_interest' => $this->input->post('special_interest'),
            'consulting_days1' => $this->input->post('consulting_days1'),
            'consulting_days2' => $this->input->post('consulting_days2'),
            'sequence_no' => $this->input->post('sequence_no'),
            'meta_title' => $this->input->post('meta_title'),
            'meta_description' => $this->input->post('meta_description'),
            'meta_keywords' => $this->input->post('meta_keywords'),
        );
         
        if(!empty($doc_path)) {
            $data['image'] = $doc_path;
        }
        
        if(!empty($opd_image_path)) {
            $data['upcoming_opds_image'] = $opd_image_path;
        }
        
        $this->doctor->update(array('id' => $get_id), $data); 
        $response = array("status" => "ok", "heading" => "Updated", "message" => "Doctor Updated Successfully.");
    }
    else
    {
        $data = array(
            'doc_cat_id' => $doc_cat_ids,
            'doc_cat_sub' => $this->input->post('doc_cat_sub'),
            'doc_name' => $this->input->post('doc_name'),
            'qualification' => $this->input->post('qualification'),
            'contact_no' => $this->input->post('contact_no'),
            'email' => $this->input->post('email'),
            'description' => $this->input->post('description'),
            'special_interest' => $this->input->post('special_interest'),
            'consulting_days1' => $this->input->post('consulting_days1'),
            'consulting_days2' => $this->input->post('consulting_days2'),
            'sequence_no' => $this->input->post('sequence_no'),
            'meta_title' => $this->input->post('meta_title'),
            'meta_description' => $this->input->post('meta_description'),
            'meta_keywords' => $this->input->post('meta_keywords'),
            'image' => $doc_path,
            'upcoming_opds_image' => $opd_image_path,
            'add_date' => date("Y-m-d H:i:s"),
            'date' => date("Y-m-d"),
            'time' => date("H:i:s"),
        );
        $insert = $this->doctor->save($data);  

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

    private function set_upload_options()
    {   
        $config = array();
        $config['upload_path'] = DOCTOR_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->doctor->get_datatables();
        $data = array();
        $no = $_POST['start'] + 1;
        foreach ($list as $doctor) {
            $row = array();
            $row[] = $no++; 
            
            // Handle multiple specialties
            $specialty_names = '';
            if(!empty($doctor->doc_cat_id)) {
                $specialty_ids = explode(',', $doctor->doc_cat_id);
                $specialty_badges = array();
                foreach($specialty_ids as $spec_id) {
                    $speciality = $this->db->get_where(TBL_SPECIALIY, array('id' => trim($spec_id)))->row();
                    if($speciality) {
                        $specialty_badges[] = '<span class="specialty-badge">' . $speciality->cat_name . '</span>';
                    }
                }
                $specialty_names = !empty($specialty_badges) ? implode(' ', $specialty_badges) : 'N/A';
            } else {
                $specialty_names = 'N/A';
            }
            $row[] = $specialty_names;
            
            $row[] = $doctor->doc_name;
            $row[] = $doctor->sequence_no;

            if(!empty($doctor->image) && file_exists(DOCTOR_PATH . "/" . $doctor->image)) {
                $img_url = base_url('../assets/images/doctors/' . $doctor->image);
                $row[] = "<img src='".$img_url."' style='width:auto; height:50px;' />";
            } else {
                $row[] = "<span class='text-muted'>-</span>";
            }

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

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

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

    if($row) {
        $data = array(
            'id' => $row->id,
            'doc_cat_id' => !empty($row->doc_cat_id) ? explode(',', $row->doc_cat_id) : array(),
            'doc_cat_sub' => isset($row->doc_cat_sub) ? $row->doc_cat_sub : '',
            'doc_name' => $row->doc_name,
            'qualification' => $row->qualification,
            'contact_no' => isset($row->contact_no) ? $row->contact_no : '',
            'email' => isset($row->email) ? $row->email : '',
            'description' => isset($row->description) ? $row->description : '',
            'special_interest' => isset($row->special_interest) ? $row->special_interest : '',
            'consulting_days1' => isset($row->consulting_days1) ? $row->consulting_days1 : '',
            'consulting_days2' => isset($row->consulting_days2) ? $row->consulting_days2 : '',
            'sequence_no' => isset($row->sequence_no) ? $row->sequence_no : '',
            'meta_title' => isset($row->meta_title) ? $row->meta_title : '',
            'meta_description' => isset($row->meta_description) ? $row->meta_description : '',
            'meta_keywords' => isset($row->meta_keywords) ? $row->meta_keywords : '',
            'image' => isset($row->image) ? $row->image : '',
            'upcoming_opds_image' => isset($row->upcoming_opds_image) ? $row->upcoming_opds_image : ''
        );

        echo json_encode($data);
    } else {
        echo json_encode(array('error' => 'Record not found'));
    }
}

    public function active($id)
    {
        $data = array();
        $sql = "update ". TBL_DOCTOR_PROFILE ." 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_DOCTOR_PROFILE ." 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, image, upcoming_opds_image, publish from ". TBL_DOCTOR_PROFILE ." where id='$get_id' and publish='1'")->row(); 
    if (isset($sql_query))
    {    
        // Delete doctor image
        if(!empty($sql_query->image))
        {
            $image_file_path = DOCTOR_PATH . "/" . $sql_query->image; 
            if(file_exists($image_file_path)) {
                unlink($image_file_path);
            }
        }
        
        // Delete OPD image
        if(!empty($sql_query->upcoming_opds_image))
        {
            $opd_image_file_path = DOCTOR_PATH . "/" . $sql_query->upcoming_opds_image; 
            if(file_exists($opd_image_file_path)) {
                unlink($opd_image_file_path);
            }
        }
    }
    $response = array("status" => "ok", "heading" => "Deleted", "message" => "Doctor Deleted Successfully.", "tbc_name" => "");
    $this->doctor->delete_by_id($get_id);  
    echo json_encode($response);  
    die;
}
    
}