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

class Branches extends CI_Controller {

    public function __construct() {
        parent::__construct();
        date_default_timezone_set("Asia/Kolkata");
        $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'] = 'Branches';
        $data['branches'] = $this->Branches_model->get_all_branches();
        $this->load->view('branches/index', $data);
    }

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

    public function store() {
        if(isset($_POST) && !empty($_POST)) {
            $this->form_validation->set_error_delimiters('', "\n");
            $this->form_validation->set_rules('branch_name', 'Branch Name', 'required');
            $this->form_validation->set_rules('branch_code', 'Branch Code', 'required|is_unique[tbl_branches.branch_code]');
            if (!empty($this->input->post('branch_email'))) {
                $this->form_validation->set_rules('branch_email', 'Email', 'valid_email');
            }
            if ($this->form_validation->run() == FALSE) {
                echo json_encode(['status' => 'error', 'message' => validation_errors()]);
                return;
            }

            $data = array(
                'branch_name' => $this->input->post('branch_name'),
                'branch_code' => $this->input->post('branch_code'),
                'branch_address' => $this->input->post('branch_address'),
                'branch_city' => $this->input->post('branch_city'),
                'branch_state' => $this->input->post('branch_state'),
                'branch_phone' => $this->input->post('branch_phone'),
                'branch_email' => $this->input->post('branch_email'),
                'status' => 'Active'
            );

            // Handle integer column which might be empty
            $pincode = $this->input->post('branch_pincode');
            $data['branch_pincode'] = ($pincode !== '') ? $pincode : NULL;

            if($this->Branches_model->insert_branch($data)) {
                echo json_encode(['status' => 'success', 'message' => 'Branch added successfully', 'redirect' => base_url('branches')]);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Failed to add branch']);
            }
        }
    }

    public function edit($id) {
        $data['page_title'] = 'Edit Branch';
        $data['branch'] = $this->Branches_model->get_branch_by_id($id);
        if (!$data['branch']) {
            show_404();
        }
        $this->load->view('branches/edit', $data);
    }

    public function update($id) {
        if(isset($_POST) && !empty($_POST)) {
            $this->form_validation->set_error_delimiters('', "\n");
            $this->form_validation->set_rules('branch_name', 'Branch Name', 'required');
            
            $current_branch = $this->Branches_model->get_branch_by_id($id);
            if ($this->input->post('branch_code') != $current_branch->branch_code) {
                $this->form_validation->set_rules('branch_code', 'Branch Code', 'required|is_unique[tbl_branches.branch_code]');
            } else {
                $this->form_validation->set_rules('branch_code', 'Branch Code', 'required');
            }

            if (!empty($this->input->post('branch_email'))) {
                $this->form_validation->set_rules('branch_email', 'Email', 'valid_email');
            }
            if ($this->form_validation->run() == FALSE) {
                echo json_encode(['status' => 'error', 'message' => validation_errors()]);
                return;
            }

            $data = array(
                'branch_name' => $this->input->post('branch_name'),
                'branch_code' => $this->input->post('branch_code'),
                'branch_address' => $this->input->post('branch_address'),
                'branch_city' => $this->input->post('branch_city'),
                'branch_state' => $this->input->post('branch_state'),
                'branch_phone' => $this->input->post('branch_phone'),
                'branch_email' => $this->input->post('branch_email'),
                'status' => $this->input->post('status')
            );

            // Handle integer column which might be empty
            $pincode = $this->input->post('branch_pincode');
            $data['branch_pincode'] = ($pincode !== '') ? $pincode : NULL;

            if($this->Branches_model->update_branch($id, $data)) {
                echo json_encode(['status' => 'success', 'message' => 'Branch updated successfully', 'redirect' => base_url('branches')]);
            } else {
                $db_error = $this->db->error();
                echo json_encode(['status' => 'error', 'message' => 'Failed to update branch', 'error' => $db_error]);
            }
        } else {
            echo json_encode(['status' => 'error', 'message' => 'No data received']);
        }
    }
}
