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

class Purchase_entry extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->_check_login();
        $this->load->model('Purchase_entry_model');
        $this->load->model('Supplier_model');
        $this->load->model('Product_model');
        $this->load->library(['form_validation', 'session']);
        $this->load->helper('url');
    }

    private function _check_login() {
        if (!$this->session->userdata('admin_logged_in')) redirect('Auth');
    }

    // ── LIST ─────────────────────────────────────────────────────────────────
    public function index() {
        $data['page_title'] = 'Purchase Entry';
        $data['breadcrumb'] = [['label' => 'Transactions'], ['label' => 'Purchase Entry', 'active' => true]];
        $data['rows']       = $this->Purchase_entry_model->getAll();
        $this->_render('purchase_entry/index', $data);
    }

    // ── CREATE ───────────────────────────────────────────────────────────────
    public function create() {
        $data['page_title'] = 'New Purchase Entry';
        $data['breadcrumb'] = [['label' => 'Purchase Entry', 'url' => 'purchase_entry'], ['label' => 'Add', 'active' => true]];
        $data['suppliers']  = $this->Supplier_model->getActive();
        $data['products']   = $this->Product_model->getActive();

        if ($this->input->post('save_purchase')) {
            $this->form_validation->set_rules('supplier_id',   'Supplier',      'required|integer');
            $this->form_validation->set_rules('purchase_date', 'Purchase Date', 'required');

            if ($this->form_validation->run() === TRUE) {
                $items = $this->_parse_items();
                if (empty($items)) {
                    $data['item_error'] = 'Please add at least one item with valid qty and rate.';
                } else {
                    $upload = $this->_handle_attachment_upload();
                    if (!$upload['status']) {
                        $data['item_error'] = $upload['error'];
                    } else {
                        $total_amount = array_sum(array_column($items, 'amount'));
                        $grand_total  = array_sum(array_column($items, 'total'));

                        $header = [
                            'supplier_id'   => $this->input->post('supplier_id'),
                            'purchase_date' => $this->input->post('purchase_date'),
                            'invoice_no'    => $this->input->post('invoice_no', TRUE),
                            'notes'         => $this->input->post('notes', TRUE),
                            'attachment'    => $upload['filename'],
                            'total_amount'  => $total_amount,
                            'grand_total'   => $grand_total,
                            'created_by'    => $this->session->userdata('admin_id'),
                        ];

                        $result = $this->Purchase_entry_model->insertWithItems($header, $items);
                        if ($result) {
                            $this->session->set_flashdata('success', 'Purchase entry saved successfully.');
                            redirect('purchase_entry');
                        } else {
                            $data['item_error'] = 'Database error. Please try again.';
                        }
                    }
                }
            }
        }

        $this->_render('purchase_entry/form', $data);
    }

    // ── EDIT ─────────────────────────────────────────────────────────────────
    public function edit($id) {
        $data['row'] = $this->Purchase_entry_model->getOne($id);
        if (!$data['row']) show_404();

        $data['page_title'] = 'Edit Purchase Entry';
        $data['breadcrumb'] = [['label' => 'Purchase Entry', 'url' => 'purchase_entry'], ['label' => 'Edit', 'active' => true]];
        $data['suppliers']  = $this->Supplier_model->getActive();
        $data['products']   = $this->Product_model->getActive();
        $data['edit_items'] = $this->Purchase_entry_model->getItems($id);

        if ($this->input->post('save_purchase')) {
            $this->form_validation->set_rules('supplier_id',   'Supplier',      'required|integer');
            $this->form_validation->set_rules('purchase_date', 'Purchase Date', 'required');

            if ($this->form_validation->run() === TRUE) {
                $items = $this->_parse_items();
                if (empty($items)) {
                    $data['item_error'] = 'Please add at least one item with valid qty and rate.';
                } else {
                    $upload = $this->_handle_attachment_upload($data['row']->attachment);
                    if (!$upload['status']) {
                        $data['item_error'] = $upload['error'];
                    } else {
                        $total_amount = array_sum(array_column($items, 'amount'));
                        $grand_total  = array_sum(array_column($items, 'total'));

                        $header = [
                            'supplier_id'   => $this->input->post('supplier_id'),
                            'purchase_date' => $this->input->post('purchase_date'),
                            'invoice_no'    => $this->input->post('invoice_no', TRUE),
                            'notes'         => $this->input->post('notes', TRUE),
                            'attachment'    => $upload['filename'],
                            'total_amount'  => $total_amount,
                            'grand_total'   => $grand_total,
                        ];

                        $this->Purchase_entry_model->updateWithItems($id, $header, $items);
                        $this->session->set_flashdata('success', 'Purchase entry updated successfully.');
                        redirect('purchase_entry');
                    }
                }
            }
        }

        $this->_render('purchase_entry/form', $data);
    }

    // ── VIEW ─────────────────────────────────────────────────────────────────
    public function view($id) {
        $data['row']   = $this->Purchase_entry_model->getOne($id);
        if (!$data['row']) show_404();
        $data['items'] = $this->Purchase_entry_model->getItems($id);
        $data['page_title'] = 'Purchase Details';
        $data['breadcrumb'] = [['label' => 'Purchase Entry', 'url' => 'purchase_entry'], ['label' => 'View', 'active' => true]];
        $this->_render('purchase_entry/view', $data);
    }

    // ── DELETE ───────────────────────────────────────────────────────────────
    public function delete($id) {
        $this->Purchase_entry_model->delete($id);
        $this->session->set_flashdata('success', 'Purchase entry deleted.');
        redirect('purchase_entry');
    }

    // ── AJAX ADD SUPPLIER ────────────────────────────────────────────────────
    public function ajax_add_supplier() {
        if (!$this->input->is_ajax_request()) show_404();

        $name    = trim($this->input->post('supplier_name'));
        $mobile  = trim($this->input->post('mobile'));
        $gst_no  = trim($this->input->post('gst_no'));
        $address = trim($this->input->post('address'));

        if (!$name) {
            echo json_encode(['status' => 'error', 'message' => 'Supplier Name is required.']);
            return;
        }
        if (!$mobile || !preg_match('/^[0-9]{10}$/', $mobile)) {
            echo json_encode(['status' => 'error', 'message' => 'Valid 10-digit Mobile Number is required.']);
            return;
        }
        if (!$address) {
            echo json_encode(['status' => 'error', 'message' => 'Address is required.']);
            return;
        }

        $data = [
            'supplier_name' => $name,
            'mobile'        => $mobile,
            'gst_no'        => $gst_no ?: NULL,
            'address'       => $address,
            'status'        => 1,
            'is_deleted'    => 0,
            'created_by'    => $this->session->userdata('admin_id'),
            'created_at'    => date('Y-m-d H:i:s'),
        ];

        $this->db->insert('supplier_master', $data);
        $new_id = $this->db->insert_id();

        if ($new_id) {
            echo json_encode(['status' => 'success', 'id' => $new_id, 'supplier_name' => $name, 'mobile' => $mobile]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Database insert failed: ' . $this->db->error()['message']]);
        }
    }

    // ── PRIVATE: handle image/pdf attachment upload ─────────────────────────
    // $existing_file: pass current attachment filename (edit) to keep it when no new file is chosen.
    private function _handle_attachment_upload($existing_file = null) {
        // No file chosen -> keep existing attachment (or NULL on create)
        if (empty($_FILES['attachment']['name'])) {
            return ['status' => true, 'filename' => $existing_file];
        }

        $upload_dir = FCPATH . 'uploads/purchase_entry/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }

        $config['upload_path']   = $upload_dir;
        $config['allowed_types'] = 'jpg|jpeg|png|pdf';
        $config['max_size']      = 5120; // 5 MB
        $config['encrypt_name']  = TRUE;

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('attachment')) {
            return ['status' => false, 'error' => $this->upload->display_errors('', '')];
        }

        $upload_data = $this->upload->data();

        // Remove old file (edit, replaced with a new one) to avoid orphan files
        if (!empty($existing_file) && file_exists($upload_dir . $existing_file)) {
            @unlink($upload_dir . $existing_file);
        }

        return ['status' => true, 'filename' => $upload_data['file_name']];
    }

    // ── PRIVATE: parse multi-row items ───────────────────────────────────────
    private function _parse_items() {
        $product_ids = $this->input->post('product_id');
        $qtys        = $this->input->post('qty');
        $rates       = $this->input->post('rate');
        $gsts        = $this->input->post('gst_percent');
        $items = [];

        if (!is_array($product_ids)) return [];

        foreach ($product_ids as $i => $pid) {
            $pid   = (int)$pid;
            $qty   = (int)($qtys[$i]  ?? 0);
            $rate  = (int)($rates[$i] ?? 0);
            $gst   = (int)($gsts[$i]  ?? 0);

            if ($pid <= 0 || $qty <= 0 || $rate <= 0) continue;

            $amount = $qty * $rate;
            $items[] = [
                'product_id'  => $pid,
                'qty'         => $qty,
                'rate'        => $rate,
                'gst_percent' => $gst,
                'amount'      => $amount,
                'total'       => $amount + ($amount * $gst / 100),
            ];
        }
        return $items;
    }

    public function print_order($id)
    {
        $data['row'] = $this->Purchase_entry_model->getOne($id);

        if (!$data['row']) {
            show_404();
        }

        $data['items'] = $this->Purchase_entry_model->getItems($id);

        $this->load->view('purchase_entry/print_order', $data);
    }

    // ── HELPER: load views ───────────────────────────────────────────────────
    private function _render($view, $data) {
        $this->load->view('layout/header', $data);
        $this->load->view('layout/sidebar', $data);
        $this->load->view($view, $data);
        $this->load->view('layout/footer', $data);
    }
}