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

class Sub_Services extends CI_Controller {


    public function __construct() {
        parent::__construct();
        if (!isset($_SESSION['qurbani_user_id']) || $_SESSION['qurbani_role'] != 'sa') {
            redirect('/admin', 'refresh');
        }

        $this->load->model('Sub_services_model', 'sub_services');
        $this->load->model('Services_model', 'services');
        $this->load->model('Departments_model', 'departments');
         $this->load->model('Settings_model', 'setup');
    }
// public function export($service_id = null) {
//     if(!$service_id){
//         $this->session->set_flashdata('error','Select a service first');
//         redirect('admin/sub_services/import');
//         return;
//     }

//     $sub_services = $this->db->select('ss.name, ss.description, f.fee, f.currency')
//                              ->from('kns1_sub_services ss')
//                              ->join('kns1_service_fees f','f.sub_service_id=ss.id','left')
//                              ->where('ss.service_id',$service_id)
//                              ->get()->result();

//     header('Content-Type: text/csv');
//     header('Content-Disposition: attachment; filename="sub_services_'.time().'.csv"');

//     $output = fopen('php://output', 'w');
//     fputcsv($output, ['Sub Service Name', 'Description', 'Fee', 'Currency']);

//     foreach($sub_services as $s){
//         fputcsv($output, [$s->name, $s->description, $s->fee, $s->currency]);
//     }
//     fclose($output);
//     exit;
// }
    public function export($service_id = null)
{
    if (!$service_id) {
        $this->session->set_flashdata('error', 'Select a service first');
        redirect('admin/sub_services/import');
        return;
    }

    // 🔹 Get service + department names
    $info = $this->db->select('s.name AS service_name, d.name AS department_name')
                     ->from('kns1_services s')
                     ->join('kns1_departments d', 'd.id = s.department_id')
                     ->where('s.id', $service_id)
                     ->get()
                     ->row();

    $service_name    = $info ? $info->service_name : 'service';
    $department_name = $info ? $info->department_name : 'department';

    // 🔹 Clean filename (no spaces/special chars)
    $department_name = preg_replace('/[^A-Za-z0-9\-]/', '_', $department_name);
    $service_name    = preg_replace('/[^A-Za-z0-9\-]/', '_', $service_name);

    $date = date('Y-m-d');

    // 🔹 Fetch sub services
    $sub_services = $this->db->select('ss.name, ss.description, f.fee, f.currency')
                             ->from('kns1_sub_services ss')
                             ->join('kns1_service_fees f','f.sub_service_id = ss.id','left')
                             ->where('ss.service_id', $service_id)
                             ->get()
                             ->result();

    // 🔹 CSV headers
    header('Content-Type: text/csv');
    header(
        'Content-Disposition: attachment; filename="' .
        $department_name . '_' . $service_name . '_' . $date . '.csv"'
    );

    $output = fopen('php://output', 'w');
    fputcsv($output, ['Sub Service Name', 'Description', 'Fee', 'Currency']);

    foreach ($sub_services as $s) {
        fputcsv($output, [
            $s->name,
            $s->description,
            $s->fee,
            $s->currency
        ]);
    }

    fclose($output);
    exit;
}



    // public function by_department($dep_id)
    // {
    //     $services = $this->db
    //         ->get_where('kns1_services', ['department_id' => $dep_id])
    //         ->result();
    //     echo json_encode($services);
    // }

    /**
     * Upload CSV temporarily into /uploads/tmp and return file name as JSON
     */
// Import flow is handled via modal on the sub_services index (no standalone view exists)
    public function import() {
        redirect('admin/sub_services');
    }

    // Get Services for a Department
    public function by_department($dep_id) {
        $services = $this->db->get_where('kns1_services', ['department_id' => $dep_id])->result();
        header('Content-Type: application/json');
        echo json_encode($services);
    }

    // Upload CSV to temporary folder
    public function upload_csv_temp() {
        $upload_dir = FCPATH.'uploads/tmp/';
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);

        $config = [
            'upload_path'   => $upload_dir,
            'allowed_types' => 'csv',
            'max_size'      => 10240,
            'file_name'     => time().'_'.preg_replace('/\s+/', '_', $_FILES['csv_file']['name']),
        ];
        $this->upload->initialize($config);

        if (!$this->upload->do_upload('csv_file')) {
            echo json_encode(['status'=>'error','message'=>strip_tags($this->upload->display_errors())]);
            return;
        }

        $upload_data = $this->upload->data();
        echo json_encode([
            'status' => 'ok',
            'file'   => $upload_data['file_name'],
            'csrf_hash' => $this->security->get_csrf_hash()
        ]);
    }

    // Process CSV import
    public function process_import() {
        $temp_file  = $this->input->post('temp_file');
        $service_id = $this->input->post('service_id');

        $file_path = FCPATH.'uploads/tmp/'.$temp_file;
        if (!file_exists($file_path)) {
            echo json_encode(['status'=>'error','message'=>'Temp CSV not found']);
            return;
        }

        $handle = fopen($file_path,'r');
        if (!$handle) {
            echo json_encode(['status'=>'error','message'=>'Could not open file']);
            return;
        }

        $header = fgetcsv($handle); // skip header
        $count_new = 0;
        $count_updated = 0;

        while(($row = fgetcsv($handle)) !== false) {
            $sub_name    = trim($row[0]);
            $description = trim($row[1]);
            $fee         = trim($row[2]);
            $currency    = trim($row[3]) ?: 'PKR';

            // Check if sub-service exists
            $sub = $this->db->get_where('kns1_sub_services', [
                'service_id'=>$service_id,
                'name'=>$sub_name
            ])->row();

            if($sub){
                $this->db->where('id',$sub->id)
                         ->update('kns1_sub_services',['description'=>$description]);
                $sub_id = $sub->id;
                $count_updated++;
            } else {
                $this->db->insert('kns1_sub_services', [
                    'service_id'=>$service_id,
                    'name'=>$sub_name,
                    'description'=>$description
                ]);
                $sub_id = $this->db->insert_id();
                $count_new++;
            }

            // Insert/update fee
            $fee_data = ['sub_service_id'=>$sub_id,'fee'=>$fee,'currency'=>$currency];
            $existing_fee = $this->db->get_where('kns1_service_fees',['sub_service_id'=>$sub_id])->row();
            if($existing_fee){
                $this->db->where('sub_service_id',$sub_id)->update('kns1_service_fees',$fee_data);
            } else {
                $this->db->insert('kns1_service_fees',$fee_data);
            }
        }

        fclose($handle);
        unlink($file_path);

        echo json_encode([
            'status'=>'ok',
            'message'=>"Import finished: $count_new new, $count_updated updated."
        ]);
    }


    // List all sub-services
    public function index() {
        
        $data['total_sub_services'] = $this->sub_services->count_all();
        $data['sub_services'] = $this->sub_services->get_all();
        $data['services'] = $this->services->get_all();
        $data['departments'] = $this->departments->get_all();

        $data['settings'] = $this->setup->get_by_id(1);

        $data['title'] = 'Sub Services';
        $data['mainContent'] = 'admin/sub_services/index';
        $this->load->view('admin/layout/master', $data);
    }

    // Add new sub-service
public function add() {
    if($this->input->post()) {
        // Insert sub-service
        $sub_service_id = $this->sub_services->insert([
            'service_id' => $this->input->post('service_id'),
            'name' => $this->input->post('name'),
            'description' => $this->input->post('description')
        ]);

        // Insert fee for this sub-service
        $fee_data = [
            'sub_service_id' => $sub_service_id,
            'fee' => $this->input->post('fee'),
            'currency' => $this->input->post('currency') ?: 'PKR'
        ];
        $this->db->insert('kns1_service_fees', $fee_data);

        $this->session->set_flashdata('message', 'Sub-service and fee added successfully.');
    }
    redirect('admin/sub_services');
}


    // Edit sub-service
public function edit() {
    if($this->input->post()) {
        $id = $this->input->post('id');

        // Update sub-service
        $this->sub_services->update($id, [
            'service_id' => $this->input->post('service_id'),
            'name' => $this->input->post('name'),
            'description' => $this->input->post('description')
        ]);

        // Update or insert fee
        $fee_data = [
            'sub_service_id' => $id,
            'fee' => $this->input->post('fee'),
            'currency' => $this->input->post('currency') ?: 'PKR'
        ];

        $existing_fee = $this->db->get_where('kns1_service_fees', ['sub_service_id' => $id])->row();
        if($existing_fee) {
            $this->db->where('sub_service_id', $id)->update('kns1_service_fees', $fee_data);
        } else {
            $this->db->insert('kns1_service_fees', $fee_data);
        }

        $this->session->set_flashdata('message', 'Sub-service updated successfully.');
    }
    redirect('admin/sub_services');
}


public function delete($id) {
    // First delete associated fees
    $this->db->where('sub_service_id', $id)->delete('kns1_service_fees');

    // Now delete the sub-service
    $this->sub_services->delete($id);

    $this->session->set_flashdata('message', 'Sub-service deleted successfully.');
    redirect('admin/sub_services');
}

    // Optional: AJAX get sub-services by service
    public function by_service($service_id = null) {
        if (!$service_id) {
            $this->output
                 ->set_content_type('application/json')
                 ->set_output(json_encode(['status' => 'error', 'message' => 'service_id missing']));
            return;
        }
        $sub_services = $this->db->get_where('kns1_sub_services', ['service_id' => $service_id])->result();
        $this->output
             ->set_content_type('application/json')
             ->set_output(json_encode(['status' => 'ok', 'sub_services' => $sub_services]));
    }
}