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

class Staff extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        if (!isset($_SESSION['qurbani_user_id'])) { 
            redirect('/admin','refresh');
        }
        
        $this->load->model('User_model', 'user');
        $this->load->model('Staff_model', 'staff');
        $this->load->model('Settings_model', 'setup');
        $this->load->model('Daily_expense_model', 'expense');
        $this->load->model('Expense_types_model', 'expense_types');

        $this->load->model('Payment_model', 'payment');
        $this->load->model('Staff_withdrawal_model', 'withdrawal');

        $this->load->helper('custom');
       }
       
  ///////////////////////
 //CUSTOMER INDEX PAGE//
///////////////////////

public function index()
{


    if (!$this->user->has_permission('staff', 'view')) {
        redirect('/admin','refresh');
    }


  $year = $this->input->get('salary_year') ?? date('Y');
$data['salary_year'] = $year;

// Fetch withdrawals grouped by month and type
$raw_withdrawals = $this->payment->get_salary_withdrawals_grouped($year);

// Labels: Jan to Dec
$monthLabels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

// Initialize arrays (index 0 to 11 for Jan to Dec)
$advanceData = array_fill(0, 12, 0);
$loanData    = array_fill(0, 12, 0);
$salaryData  = array_fill(0, 12, 0);

// Fill based on month (1 = Jan = index 0)
foreach ($raw_withdrawals as $row) {
    $index = (int)$row->month - 1;
    if ($row->staff_withdrawal_type == 1) {
        $advanceData[$index] = (float)$row->total;
    } elseif ($row->staff_withdrawal_type == 2) {
        $loanData[$index] = (float)$row->total;
    } elseif ($row->staff_withdrawal_type == 3) {
        $salaryData[$index] = (float)$row->total;
    }
}

// Pass to view
$data['monthLabels']  = $monthLabels;
$data['advanceData']  = $advanceData;
$data['loanData']     = $loanData;
$data['salaryData']   = $salaryData;


    // Other existing data
    $data['staff'] = $this->staff->get_all();
    $data['settings'] = $this->setup->get_by_id(1);
    $data['title'] = 'All Staff Members';
    $data['mainContent'] = 'admin/staff/index';
    $this->load->view('admin/layout/master', $data);     
}




  /////////////////////////
 //ADD NEW CUSTOMER PAGE//
/////////////////////////

    public function add()
    {
        if (!$this->user->has_permission('staff', 'add')) {
            redirect('/admin', 'refresh');
         return;
            } 

        if ($_SERVER['REQUEST_METHOD'] == 'POST')
        {
            $id = $this->input->post('id');
            $staff_name = $this->input->post('staff_name');
            $father_name = $this->input->post('father_name');
            $phone = $this->input->post('phone');
            $cnic = $this->input->post('cnic');
            $address = $this->input->post('address');
            $salary = $this->input->post('salary');
            $position = $this->input->post('position');
            $staff_status = $this->input->post('staff_status');
            $note = $this->input->post('note');

            $options = [
                'id' => $id,
                'staff_name' => $staff_name,
                'father_name' => $father_name,
                'phone' => $phone,
                'cnic' => $cnic,
                'address' => $address,
                'salary' => $salary,
                'position' => $position,
                'staff_status' => $staff_status,
                'note' => $note,
            ];

             $affected = $this->staff->create($options);

             if ($affected) {

                // NOTE: user account auto-creation hata diya — pehle `$role` undefined tha
                // aur User link banata hi nahi tha (role = NULL). User account Users section
                // se manually banao.
                $this->session->set_flashdata('message', 'Staff member added successfully.');
                redirect(base_url().'admin/staff');
            }

             else {
                $this->session->set_flashdata('error', 'Something Went Wrong! Please Try Again.');
                redirect(base_url().'admin/staff');
            }
        }
        // No standalone add page — adding is done via the modal on the staff index
        redirect(base_url().'admin/staff');
    }

 

    public function view($id)
    {

        if (!$this->user->has_permission('staff', 'edit')) {
            redirect('/admin', 'refresh');
         return;
            } 
    
        if ($_SERVER['REQUEST_METHOD'] == 'POST')
        
        {

            $staff_name = $this->input->post('staff_name');
            $father_name = $this->input->post('father_name');
            $phone = $this->input->post('phone');
            $cnic = $this->input->post('cnic');
            $address = $this->input->post('address');
            $salary = $this->input->post('salary');
            $position = $this->input->post('position');
            $staff_status = $this->input->post('staff_status');
            $note = $this->input->post('note');

            $options = [
                'staff_name' => $staff_name,
                'father_name' => $father_name,
                'phone' => $phone,
                'cnic' => $cnic,
                'address' => $address,
                'salary' => $salary,
                'position' => $position,
                'staff_status' => $staff_status,
                'note' => $note,
            ];

             $affected = $this->staff->view($id, $options);

             if ($affected) {

                $data['message'] = "Staff Edit successfully";
                redirect(base_url().'admin/staff/view/'.$id);
            } else {
                $data['error'] = "Something Went Wrong! Please Try Again.";
            }
        }

        $data['payments'] = $this->payment->get_payments_by_staff($id); // Load staff-specific payments
        $data['staff'] = $this->staff->get_all_by($id);
        $data['settings'] = $this->setup->get_all();
        $data['title'] = 'Staff Profile';
        $data['mainContent'] = 'admin/staff/view';
        $this->load->view('admin/layout/master', $data);        
    }




public function delete($id)
    {
       
        if (!$this->user->has_permission('staff', 'delete')) {
            redirect('/admin', 'refresh');
         return;
            } 

        $affected = $this->staff->destroy($id);
        if($affected)
        {
            $data['message'] = "Deleted Successfully";
        }
        redirect(base_url().'admin/staff');
    }

public function add_withdrawal()
{
    // ✅ Permission check
    if (!$this->user->has_permission('payment', 'add')) {
        redirect('/admin', 'refresh');
        return;
    }

// ✅ Form submission check
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $data = [
        'staff_id'               => $this->input->post('staff_id'),
        'staff_withdrawal_date'  => $this->input->post('staff_withdrawal_date'),
        'staff_withdrawal_type'  => $this->input->post('staff_withdrawal_type'),
        'staff_withdrawal_amount'=> $this->input->post('staff_withdrawal_amount'),
        'note'                   => $this->input->post('note'),
    ];

    // ✅ Create withdrawal
    $insert_id = $this->withdrawal->create($data);

    if ($insert_id) {
        // ✅ Insert into payment table
        $payment = [
            'payment_module'   => 'Staff',
            'module_id'        => $insert_id, // withdrawal record id
            'pay_customer_id'  => $data['staff_id'],
            'pay_date'         => $data['staff_withdrawal_date'],
            'credit'           => $data['staff_withdrawal_amount'],
            'user_id'          => $_SESSION['qurbani_user_id']
        ];
        $this->payment->create($payment);

        // ✅ Insert into expense table
        $expenses = [
            'expense_type_id'      => 0,
            'sub_expense_type_id'  => $data['staff_withdrawal_type'],
            'staff_id'             => $data['staff_id'],
            'rate'                 => $data['staff_withdrawal_amount'],
            'quantity'             => 1,
            'amount'               => $data['staff_withdrawal_amount'],
            'note'                 => $data['note'],
            'date'                 => $data['staff_withdrawal_date']
        ];
        $this->expense->create($expenses);

        // ✅ Success message
        $this->session->set_flashdata('message', 'Staff payment added successfully.');
    } else {
        $this->session->set_flashdata('error', 'Something went wrong!');
    }

    redirect('admin/staff/index');
}

}

}