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

class Expense extends CI_Controller {

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

        $this->load->model('Daily_expense_model', 'expense');
        $this->load->model('Expense_types_model', 'expense_types');
        $this->load->model('Staff_model', 'staff');
        $this->load->model('Payment_model', 'payment');
        $this->load->model('Settings_model', 'setup');
        $this->load->model('User_model', 'user');
    }

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

        $selected_month = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');
        $selected_year  = isset($_GET['year'])  ? (int)$_GET['year']  : (int)date('Y');
        $bar_year       = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');
        
        $data['selected_month']  = $selected_month;
        $data['selected_year']   = $selected_year;
        $data['bar_year']        = $bar_year;

        $data['type_wise_expense'] = $this->expense->get_expense_type_summary($selected_month, $selected_year);
        $data['daily_expense']   = $this->expense->get_all_by_month_year($selected_month, $selected_year);
        $data['monthly_expense'] = $this->expense->get_monthly_expense_by_year($bar_year);

        $data['staff']           = $this->staff->get_all();
        $data['settings']        = $this->setup->get_by_id(1);
        $data['sub_expense_types']   = $this->expense_types->sub_get_all();
        $data['expense_types']   = $this->expense_types->get_all();

        $data['title']           = 'Expense Management';
        $data['mainContent']     = 'admin/expense/index';
        $this->load->view('admin/layout/master', $data);
    }

    public function add()
    {

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

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $data = [
                'expense_type_id'     => $this->input->post('expense_type_id'),
                'sub_expense_type_id' => $this->input->post('sub_expense_type_id'),
                'staff_id'            => $this->input->post('staff_id'),
                'rate'                => $this->input->post('rate'),
                'quantity'            => $this->input->post('quantity'),
                'amount'              => $this->input->post('amount'),
                'note'                => $this->input->post('note'),
                'date'                => $this->input->post('date')
            ];

            $insert_id = $this->expense->create($data);

            if ($insert_id) {
                $payment = [
                    'payment_module'   => 'Expense',
                    'module_id'        => $data['expense_type_id'],
                    'pay_customer_id'  => $data['sub_expense_type_id'],
                    'pay_date'         => $data['date'],
                    'credit'           => $data['amount'],
                    'user_id'          => $_SESSION['qurbani_user_id']
                ];
                $this->payment->create($payment);

                $this->session->set_flashdata('message', 'Expense added successfully.');
            } else {
                $this->session->set_flashdata('error', 'Something went wrong!');
            }

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

   public function edit()
{

    if (!$this->user->has_permission('expense', 'edit')) {
            redirect('/admin', 'refresh');
         return;
            }

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $expense_id = $this->input->post('daily_expense_id'); // coming from hidden field
        $rate       = $this->input->post('rate');
        $quantity   = $this->input->post('quantity');
        $amount     = $this->input->post('amount');
        $note       = $this->input->post('note');
        $date       = $this->input->post('date');
        $old_amount = $this->input->post('old_amount');

        $amount = $amount ?: ($rate * $quantity);

        $update_data = [
            'date'     => $date,
            'rate'     => $rate,
            'quantity' => $quantity,
            'amount'   => $amount,
            'note'     => $note
        ];

        $updated = $this->expense->update($expense_id, $update_data);

        if ($updated && $old_amount != $amount) {
            $adjust = [
                'payment_module' => 'expense_edit',
                'module_id'      => $expense_id,
                'user_id'        => $_SESSION['qurbani_user_id']
            ];
            if ($amount > $old_amount) {
                $adjust['credit'] = $amount - $old_amount;
            } else {
                $adjust['debit'] = $old_amount - $amount;
            }

            $this->payment->create($adjust);
        }

        $this->session->set_flashdata('message', 'Expense updated successfully');
        redirect('admin/expense/index');
    }
}

    public function delete($id)
    {

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

        $expense = $this->expense->get_by($id);
        $deleted = $this->expense->destroy($id);

        if ($deleted) {
            $this->payment->create([
                'payment_module' => 'expense_delete',
                'module_id'      => $id,
                'user_id'        => $_SESSION['qurbani_user_id'],
                'debit'          => $expense->amount
            ]);
            $this->session->set_flashdata('message', 'Deleted successfully.');
        } else {
            $this->session->set_flashdata('error', 'Failed to delete.');
        }

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

    public function add_expense_type()
    {

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

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $options = [
                'id'           => $this->input->post('id'),
                'expense_type' => $this->input->post('expense_type'),
                'note'         => $this->input->post('note')
            ];

            $this->expense_types->create($options);
            $this->session->set_flashdata('message', 'Expense Type Added successfully');
            redirect('admin/settings/index#expenseTab');
        }
    }

 public function update_type()
{

    if (!$this->user->has_permission('expense', 'edit')) {
            redirect('/admin', 'refresh');
         return;
            }

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $id = $this->input->post('id');
        $data = [
            'expense_type' => $this->input->post('expense_type'),
        ];
        $this->db->where('id', $id);
        $this->db->update('kns1_expense_types', $data);
        $this->session->set_flashdata('message', 'Expense Type updated successfully');
        redirect('admin/settings/index#expenseTab');
    }
}


    public function delete_expense_type($id)
    {

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

        $this->db->delete('kns1_expense_types', ['id' => $id]);
        $this->session->set_flashdata('message', 'Expense Type deleted successfully');
        redirect('admin/settings/index#expenseTab');
    }

    public function add_sub_expense_type()
    {

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

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $options = [
                'expense_type_id'   => $this->input->post('expense_type_id'),
                'sub_expense_type'  => $this->input->post('sub_expense_type'),
                'note'              => $this->input->post('note')
            ];

            $this->db->insert('kns1_sub_expense_types', $options);
            $this->session->set_flashdata('message', 'Sub Expense Type Added successfully');
            redirect('admin/settings/index#expenseTab');
        }
    }

    public function update_subtype()
{

    if (!$this->user->has_permission('expense', 'edit')) {
            redirect('/admin', 'refresh');
         return;
            }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $id = $this->input->post('id');
        $data = [
            'expense_type_id'   => $this->input->post('expense_type_id'),
            'sub_expense_type'  => $this->input->post('sub_expense_type'),
            'note'              => $this->input->post('note')
        ];
        $this->db->where('id', $id);
        $this->db->update('kns1_sub_expense_types', $data);
        $this->session->set_flashdata('message', 'Sub Expense Type updated successfully');
        redirect('admin/settings/index#expenseTab');
    }
}


    public function delete_sub_expense_type($id)
    {

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

        $this->db->delete('kns1_sub_expense_types', ['id' => $id]);
        $this->session->set_flashdata('message', 'Sub Expense Type deleted successfully');
        redirect('admin/settings/index#expenseTab');
    }

    public function get_sub_expense_types($expense_type_id = null)
    {
        if (!$this->user->has_permission('expense', 'view')) {
            redirect('/admin', 'refresh');
         return;
            }

        if (!$expense_type_id) {
            echo json_encode([]);
            return;
        }

        $this->db->where('expense_type_id', $expense_type_id);
        $query = $this->db->get('kns1_sub_expense_types');
        echo json_encode($query->result());
    }
}
