<?php

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

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

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

        if ($query->num_rows() > 0) {
            $row = $query->row();
            
            $data = [
                'id' => $row->id,
                'name' => $row->cat_name,
                'description' => $row->description,
                'sequence_no' => $row->sequence_no
            ];

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

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

    if (!$speciality_name) {
        echo json_encode([
            "status" => "error",
            "message" => "Speciality name required"
        ]);
        exit;
    }

    $speciality_name = urldecode($speciality_name);
    $speciality_name = trim($speciality_name);

    // Get speciality details
    $speciality = $this->db
        ->select('id, cat_name')
        ->where('cat_name', $speciality_name)
        ->where('status', '1')
        ->get(TBL_SPECIALIY)
        ->row();

    if (!$speciality) {
        echo json_encode([
            "status" => "error",
            "message" => "Speciality not found"
        ]);
        exit;
    }

    // Build query with multiple conditions
    $this->db->select('*');
    $this->db->from(TBL_DOCTOR_PROFILE);
    $this->db->where('status', '1');
    
    // Use FIND_IN_SET for comma-separated IDs OR check if specialty is in doc_cat_sub
    $this->db->group_start();
    $this->db->where("FIND_IN_SET('{$speciality->id}', doc_cat_id) >", 0, false);
    $this->db->or_where('doc_cat_id', $speciality->id);
    $this->db->or_like('doc_cat_sub', $speciality_name);
    $this->db->group_end();
    
    $this->db->order_by('sequence_no', 'ASC');
    
    $query = $this->db->get();

    $data = [];
    foreach ($query->result() as $row) {
        $data[] = [
            "id" => $row->id,
            "name" => $row->doc_name,
            "qualification" => $row->qualification,
            "specialty" => $row->doc_cat_sub,
            "category_id" => $row->doc_cat_id,
            "image_url" => !empty($row->image)
                ? base_url("../assets/images/doctors/" . $row->image)
                : base_url("../assets/images/doctors/default-image.JPG"),
        ];
    }

    echo json_encode([
        "status" => "success",
        "speciality" => $speciality->cat_name,
        "data" => $data,
        "count" => count($data)
    ]);
    exit;
}
    public function api_specialities()
    {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
        header("Access-Control-Allow-Headers: Content-Type");
        header("Content-Type: application/json");

        try {
            $query = $this->db
                ->where('status', '1')
                ->where('publish', '1')
                ->order_by('sequence_no', 'ASC')
                ->get(TBL_SPECIALIY);

            $data = [];

            if ($query->num_rows() > 0) {
                foreach ($query->result() as $row) {
                    $data[] = [
                        "id" => $row->id,
                        "name" => $row->cat_name,
                        "description" => $row->description,
                        "sequence_no" => $row->sequence_no
                    ];
                }
            }

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

        } catch (Exception $e) {
            echo json_encode([
                "status" => "error",
                "message" => $e->getMessage(),
                "data" => []
            ]);
        }
        exit;
    }

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

    public function submit()
    {
         
        date_default_timezone_set('Asia/Calcutta'); 
        $get_id = $this->input->post('id');  
       

        if($get_id > 0)
        { 
            $data = array(
                'cat_name' => ucwords(strtolower($this->input->post('cat_name'))),  
                'sequence_no' => $this->input->post('sequence_no'), 
                'description' => $this->input->post('description'), 
                // 'update_uid' => $this->session->userdata('user_id'),
                'date_time' => date("Y-m-d H:i:s"),  
            );
            $this->category->update(array('id' => $get_id), $data); 
            $response = array("status" => "ok", "heading" => "Update", "message" => "Data Update Successfully.");
        }
        else
        {
            $data = array(
                'cat_name' => ucwords(strtolower($this->input->post('cat_name'))),  
                'sequence_no' => $this->input->post('sequence_no'), 
                'description' => $this->input->post('description'), 
                  
                // 'add_uid' => $this->session->userdata('user_id'),
                'date_time' => date("Y-m-d H:i:s"),
                 
            );
            $insert = $this->category->save($data);  

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

    public function list()
    { 
        $list = $this->category->get_datatables();
        $data = array();
        $no = $_POST['start'] + 1;
        foreach ($list as $category) {
            $row = array();
            $row[] = $no++; 
            $row[] = $category->cat_name;
           $row[] = '<div>'.$category->description.'</div>';
            $row[] = $category->sequence_no; 
 

            $row[] = date("d-m-Y g:i A", strtotime($category->date_time));
            $url = base_url();  
            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" => $_POST['draw'],
                        "recordsTotal" => $this->category->count_all(),
                        "recordsFiltered" => $this->category->count_filtered(),
                        "data" => $data,
                ); 
        echo json_encode($output);
    }

     public function edit($id)
    {
        $data['s_data'] = $this->category->get_by_id($id);
        $data['id'] =  $data['s_data']->id;
        $data['cat_name'] =  $data['s_data']->cat_name;
        $data['description'] =  $data['s_data']->description;         
        $data['sequence_no'] =  $data['s_data']->sequence_no;         
        echo json_encode($data); 
    }

    public function active($id)
    {
        $data = array();
        $sql = "update ". TBL_SPECIALIY ." 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_SPECIALIY ." set status='0' where id ='".$id."'";       
        $res = $this->db->query($sql);
        $data[] = "sucess";
        die(json_encode($data));
    }

    public function delete($id)
    {
        $get_id = $id; 
        $response = array("status" => "ok", "heading" => "Deleted", "message" => "Record Delete Successfully.", "tbc_name" => "");
        $this->category->delete_by_id($get_id);  
        echo json_encode($response);  
        die;
    }
  

}
