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

class Users extends CI_Controller {

    public function __construct() {
        parent::__construct();
        date_default_timezone_set("Asia/Kolkata");
        $this->load->model('Users_model');
        $this->load->model('Branches_model');
        $this->load->library('form_validation');

        if(!$this->session->userdata('is_logged_in') || $this->session->userdata('role') != 'Super Admin') {
            redirect(base_url('login'));
        }
    }

    public function index() {
        $data['page_title'] = 'Users';
        $data['users'] = $this->Users_model->get_all_users();
        $this->load->view('users/index', $data);
    }

    public function add() {
        $data['page_title'] = 'Add User';
        $data['branches'] = $this->Branches_model->get_all_branches();
        $this->load->view('users/add', $data);
    }

    public function store() {
        if(isset($_POST) && !empty($_POST)) {
            $this->form_validation->set_error_delimiters('', "\n");
            $this->form_validation->set_rules('name', 'Full Name', 'required');
            $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[tbl_admin.email]');
            $this->form_validation->set_rules('mobile', 'Mobile', 'required|numeric|min_length[10]|max_length[12]');
            $this->form_validation->set_rules('password', 'Password', 'required|min_length[8]');
            $this->form_validation->set_rules('role', 'Role', 'required');

            if ($this->form_validation->run() == FALSE) {
                echo json_encode(['status' => 'error', 'message' => validation_errors()]);
                return;
            }

            $data = array(
                'name' => trim($this->input->post('name')),
                'email' => trim($this->input->post('email')),
                'mobile' => trim($this->input->post('mobile')),
                'password' => trim($this->input->post('password')),
                'role' => $this->input->post('role'),
                'status' => 'Active'
            );

            $branch_id = $this->input->post('branch_id');
            $data['branch_id'] = ($branch_id !== '') ? $branch_id : NULL;

            if($this->Users_model->insert_user($data)) {
                echo json_encode(['status' => 'success', 'message' => 'User added successfully', 'redirect' => base_url('users')]);
            } else {
                $db_error = $this->db->error();
                log_message('error', 'User insert failed: ' . print_r($db_error, true));
                echo json_encode(['status' => 'error', 'message' => 'Failed to add user', 'db_error' => $db_error]);
            }
        }
    }

    public function edit($id) {
        $data['page_title'] = 'Edit User';
        $data['user'] = $this->Users_model->get_user_by_id($id);
        $data['branches'] = $this->Branches_model->get_all_branches();
        if (!$data['user']) {
            show_404();
        }
        $this->load->view('users/edit', $data);
    }

    public function update($id) {
        if(isset($_POST) && !empty($_POST)) {
            $this->form_validation->set_error_delimiters('', "\n");
            $this->form_validation->set_rules('name', 'Full Name', 'required');
            
            $current_user = $this->Users_model->get_user_by_id($id);
            if ($this->input->post('email') != $current_user->email) {
                $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[tbl_admin.email]');
            } else {
                $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
            }
            
            $this->form_validation->set_rules('mobile', 'Mobile', 'required|numeric|min_length[10]|max_length[15]');
            
            if (!empty($this->input->post('password'))) {
                $this->form_validation->set_rules('password', 'Password', 'min_length[6]');
            }
            
            $this->form_validation->set_rules('role', 'Role', 'required');

            if ($this->form_validation->run() == FALSE) {
                echo json_encode(['status' => 'error', 'message' => validation_errors()]);
                return;
            }

            $data = array(
                'name' => trim($this->input->post('name')),
                'email' => trim($this->input->post('email')),
                'mobile' => trim($this->input->post('mobile')),
                'role' => $this->input->post('role'),
                'status' => $this->input->post('status')
            );
            
            $branch_id = $this->input->post('branch_id');
            $data['branch_id'] = ($branch_id !== '') ? $branch_id : NULL;
            
            if (!empty(trim($this->input->post('password')))) {
                $data['password'] = trim($this->input->post('password'));
            }

            if($this->Users_model->update_user($id, $data)) {
                echo json_encode(['status' => 'success', 'message' => 'User updated successfully', 'redirect' => base_url('users')]);
            } else {
                $db_error = $this->db->error();
                log_message('error', 'User update failed: ' . print_r($db_error, true));
                echo json_encode(['status' => 'error', 'message' => 'Failed to update user', 'db_error' => $db_error]);
            }
        }
    }
}
