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

class Departments extends CI_Controller {

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

        $this->load->model('User_model', 'user');
        $this->load->model('Settings_model', 'setup');
        $this->load->model('Payment_model', 'payment');
        $this->load->model('Departments_model', 'dept');
    }

    // public function index()
    // {
    //     $data['total_departments'] = $this->dept->count_all();
    //     $data['departments'] = $this->dept->get_all();
    //     $data['settings'] = $this->setup->get_by_id(1);
    //     $data['title'] = 'Departments';
    //     $data['mainContent'] = 'admin/departments/index';
    //     $this->load->view('admin/layout/master', $data);
    // }

public function add()
{
    if ($this->input->post()) {
        $insert = $this->db->insert('kns1_departments', [
            'name' => $this->input->post('name'),
            'description' => $this->input->post('description')
        ]);

        if ($insert) {
            $this->session->set_flashdata('message', 'Department added successfully.');
        } else {
            $this->session->set_flashdata('error', 'Failed to add department. Please try again.');
        }
    }
    redirect('admin/settings#departmentsTab');
}

public function edit()
{
    if ($this->input->post()) {
        $this->db->where('id', $this->input->post('id'));
        $update = $this->db->update('kns1_departments', [
            'name' => $this->input->post('name'),
            'description' => $this->input->post('description')
        ]);

        if ($update) {
            $this->session->set_flashdata('message', 'Department updated successfully.');
        } else {
            $this->session->set_flashdata('error', 'Failed to update department. Please try again.');
        }
    }
    redirect('admin/settings#departmentsTab');
}

    public function delete($id)
    {

        $this->db->delete('kns1_departments', ['id' => $id]);
        $this->session->set_flashdata('message', 'Department deleted successfully.');
        redirect('admin/settings#departmentsTab');
    }

}
