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

class Tailoring_order extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->_check_login();
        $this->load->model('Tailoring_order_model');
        $this->load->model('Customer_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'] = 'Tailoring Orders';
        $data['breadcrumb'] = [['label' => 'Transactions'], ['label' => 'Tailoring Orders', 'active' => true]];
        $data['rows']       = $this->Tailoring_order_model->getAll();
        $this->_render('tailoring_order/index', $data);
    }

    // ── CREATE ───────────────────────────────────────────────────────────────
    public function create() {
        $data['page_title'] = 'New Tailoring Order';
        $data['breadcrumb'] = [['label' => 'Tailoring Orders', 'url' => 'tailoring_order'], ['label' => 'Add', 'active' => true]];
        $data['customers']  = $this->Customer_model->getActive();
        $data['order_no']   = $this->Tailoring_order_model->generateOrderNo();

        if ($this->input->post('save_order')) {
            $this->form_validation->set_rules('customer_id',    'Customer',       'required|integer');
            $this->form_validation->set_rules('order_date',     'Order Date',     'required');
            $this->form_validation->set_rules('delivery_date',  'Delivery Date',  'required');

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

                    $header = [
                        'order_no'      => $data['order_no'],
                        'customer_id'   => $this->input->post('customer_id'),
                        'order_date'    => $this->input->post('order_date'),
                        'delivery_date' => $this->input->post('delivery_date'),
                        'advance_paid'  => (int)$this->input->post('advance_paid') ?: 0,
                        'total_charge'  => $grand_total,
                        'notes'         => $this->input->post('notes', TRUE),
                        'order_status'  => $this->input->post('status', TRUE) ?: 'Pending',
                        'created_by'    => $this->session->userdata('admin_id'),
                    ];

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

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

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

        $data['page_title'] = 'Edit Tailoring Order';
        $data['breadcrumb'] = [['label' => 'Tailoring Orders', 'url' => 'tailoring_order'], ['label' => 'Edit', 'active' => true]];
        $data['customers']  = $this->Customer_model->getActive();
        $data['edit_items'] = $this->Tailoring_order_model->getItems($id);

        if ($this->input->post('save_order')) {
            $this->form_validation->set_rules('customer_id',    'Customer',       'required|integer');
            $this->form_validation->set_rules('order_date',     'Order Date',     'required');
            $this->form_validation->set_rules('delivery_date',  'Delivery Date',  'required');

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

                    $header = [
                        'customer_id'   => $this->input->post('customer_id'),
                        'order_date'    => $this->input->post('order_date'),
                        'delivery_date' => $this->input->post('delivery_date'),
                        'advance_paid'  => (int)$this->input->post('advance_paid') ?: 0,
                        'total_charge'  => $grand_total,
                        'notes'         => $this->input->post('notes', TRUE),
                        'order_status'  => $this->input->post('status', TRUE) ?: 'Pending',
                    ];

                    $this->Tailoring_order_model->updateWithItems($id, $header, $items);
                    $this->session->set_flashdata('success', 'Tailoring order updated.');
                    redirect('tailoring_order');
                }
            }
        }

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

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

    // ── DELETE ───────────────────────────────────────────────────────────────
    public function delete($id) {
        $this->Tailoring_order_model->delete($id);
        $this->session->set_flashdata('success', 'Tailoring order deleted.');
        redirect('tailoring_order');
    }

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

        $name    = trim($this->input->post('customer_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' => 'Customer 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 = [
            'customer_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('customer_master', $data);
        $new_id = $this->db->insert_id();

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

    // ── PRIVATE: parse garment items ─────────────────────────────────────────
    private function _parse_items() {
        $garment_types = $this->input->post('garment_type');
        $descriptions  = $this->input->post('description');
        $measurements  = $this->input->post('measurements');
        $qtys          = $this->input->post('qty');
        $rates         = $this->input->post('rate');
        $items = [];

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

        foreach ($garment_types as $i => $gtype) {
            $gtype = trim($gtype);
            $qty   = (int)($qtys[$i]  ?? 0);
            $rate  = (int)($rates[$i] ?? 0);

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

            $measurement_json = $measurements[$i] ?? '';
            // Sanity check: keep only if it's valid JSON, else store empty
            if ($measurement_json !== '' && json_decode($measurement_json) === NULL) {
                $measurement_json = '';
            }

            $items[] = [
                'garment_type' => $gtype,
                'description'  => trim($descriptions[$i] ?? ''),
                'measurements' => $measurement_json,
                'qty'          => $qty,
                'rate'         => $rate,
                'amount'       => $qty * $rate,
            ];
        }
        return $items;
    }

    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);
    }
}