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

class Product extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model(['Product_model', 'Category_model', 'Unit_model']);
    }

    private function _get_id() {
        $s3 = $this->uri->segment(3);
        $s4 = $this->uri->segment(4);
        return is_numeric($s3) ? (int)$s3 : (is_numeric($s4) ? (int)$s4 : NULL);
    }

    public function index()
    {
        $data['page_title']  = 'Product Master';
        $data['breadcrumb']  = [['label' => 'Masters'], ['label' => 'Product', 'active' => true]];
        $data['productdata'] = $this->Product_model->selectall();
        $this->load->view('layout/header', $data);
        $this->load->view('layout/sidebar', $data);
        $this->load->view('product/index', $data);
        $this->load->view('layout/footer', $data);
    }

    public function create()
    {
        $data['page_title'] = 'Add Product';
        $data['page_js']    = 'productCreate.js';
        $data['breadcrumb'] = [['label' => 'Product', 'url' => 'product'], ['label' => 'Add', 'active' => true]];
        $data['categories'] = $this->Category_model->getActive();
        $data['units']      = $this->Unit_model->getActive();
        $this->load->view('layout/header', $data);
        $this->load->view('layout/sidebar', $data);
        $this->load->view('product/form', $data);
        $this->load->view('layout/footer', $data);
    }

    public function edit()
    {
        $id = $this->_get_id();
        $data['productdata'] = $this->Product_model->getbyid($id);
        if (empty($data['productdata'])) { show_404(); }
        $data['page_title'] = 'Edit Product';
        $data['page_js']    = 'productCreate.js';
        $data['breadcrumb'] = [['label' => 'Product', 'url' => 'product'], ['label' => 'Edit', 'active' => true]];
        $data['categories'] = $this->Category_model->getActive();
        $data['units']      = $this->Unit_model->getActive();
        $this->load->view('layout/header', $data);
        $this->load->view('layout/sidebar', $data);
        $this->load->view('product/form', $data);
        $this->load->view('layout/footer', $data);
    }

    public function view()
    {
        $id = $this->_get_id();
        $data['productdata'] = $this->Product_model->getbyid($id);
        if (empty($data['productdata'])) { show_404(); }
        $data['page_title'] = 'View Product';
        $data['breadcrumb'] = [['label' => 'Product', 'url' => 'product'], ['label' => 'View', 'active' => true]];
        $this->load->view('layout/header', $data);
        $this->load->view('layout/sidebar', $data);
        $this->load->view('product/view', $data);
        $this->load->view('layout/footer', $data);
    }

    public function insert()
    {
        $fields = [
            'product_code'  => $this->input->post('product_code'),
            'product_name'  => $this->input->post('product_name'),
            'category_id'   => $this->input->post('category_id'),
            'unit_id'       => $this->input->post('unit_id'),
            'purchase_rate' => $this->input->post('purchase_rate'),
            'sale_rate'     => $this->input->post('sale_rate'),
            'gst_percent'   => $this->input->post('gst_percent') ?: 0,
            'opening_stock' => $this->input->post('opening_stock') ?: 0,
            'current_stock' => $this->input->post('opening_stock') ?: 0,
            'status'        => $this->input->post('status'),
            'is_deleted'    => 0,
            'created_date'  => date('Y-m-d H:i:s'),
        ];
        $this->Product_model->insert($fields);
        echo json_encode(['status' => 'success']);
    }

    public function updatedata()
    {
        $id = $this->input->post('id');
        $fields = [
            'product_code'  => $this->input->post('product_code'),
            'product_name'  => $this->input->post('product_name'),
            'category_id'   => $this->input->post('category_id'),
            'unit_id'       => $this->input->post('unit_id'),
            'purchase_rate' => $this->input->post('purchase_rate'),
            'sale_rate'     => $this->input->post('sale_rate'),
            'gst_percent'   => $this->input->post('gst_percent') ?: 0,
            'opening_stock' => $this->input->post('opening_stock') ?: 0,
            'status'        => $this->input->post('status'),
            'modified_date' => date('Y-m-d H:i:s'),
        ];
        $this->Product_model->update($id, $fields);
        echo json_encode(['status' => 'success']);
    }

    public function delete()
    {
        $id = $this->_get_id();
        if (empty($id)) {
            $this->session->set_flashdata('error', 'Invalid ID.');
            redirect('product');
            return;
        }

        $this->db->db_debug = FALSE;
        $deleted = $this->Product_model->delete($id);

        if ($deleted) {
            $this->session->set_flashdata('success', 'Product permanently deleted.');
        } else {
            $error = $this->db->error();
            if (!empty($error['code'])) {
                $this->session->set_flashdata('error', 'हे product आधीच purchase/sale entry मध्ये वापरले आहे, त्यामुळे delete करता येत नाही.');
            } else {
                $this->session->set_flashdata('error', 'Product सापडले नाही किंवा आधीच delete झाले आहे.');
            }
        }
        redirect('product');
    }

    public function toggle_status()
    {
        $id = $this->_get_id();
        if (!empty($id)) {
            $row = $this->Product_model->getbyid($id);
            if (!empty($row)) {
                $new_status = $row[0]->status == 1 ? 0 : 1;
                $this->Product_model->update($id, ['status' => $new_status]);
                $this->session->set_flashdata('success', 'Status updated.');
            }
        }
        redirect('product');
    }
}
