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

class Dashboard extends CI_Controller {

    public function __construct() {
        parent::__construct();
        if (!$this->session->userdata('admin_logged_in')) {
            redirect('Auth');
        }
        $this->load->model([
            'Category_model', 'Unit_model', 'Product_model',
            'Customer_model', 'Supplier_model',
            'Purchase_entry_model', 'Sales_billing_model','Quotation_model','Tailoring_order_model',
        ]);
    }

    public function index() {
        $data['page_title'] = 'Dashboard';

        // Masters counts
        $data['total_products']   = $this->Product_model->count();
        $data['total_customers']  = $this->Customer_model->count();
        $data['total_suppliers']  = $this->Supplier_model->count();
        $data['total_categories'] = $this->Category_model->count();
        $data['total_units']      = $this->Unit_model->count();
        $data['active_products']  = $this->Product_model->count(['status' => 1]);

        // Transaction stats
        $data['total_purchase_amt']   = $this->Purchase_entry_model->getTotalAmount();
        $data['total_sales_amt']      = $this->Sales_billing_model->getTotalSales();
        $data['total_quotations']     = $this->db->count_all('quotation_master');
        $data['total_orders']         = $this->Tailoring_order_model->count();
        $data['pending_orders']       = $this->Tailoring_order_model->countByStatus('Pending');
        $data['delivered_orders']     = $this->Tailoring_order_model->countByStatus('Delivered');
        $data['inprogress_orders']    = $this->Tailoring_order_model->countByStatus('In Progress');

        // Today's sales
        $data['today_sales'] = $this->Sales_billing_model->getTotalSales([
            'DATE(bill_date)' => date('Y-m-d'),
        ]);

        // This month sales
        $data['month_sales'] = $this->Sales_billing_model->getTotalSales([
            'MONTH(bill_date)' => date('m'),
            'YEAR(bill_date)'  => date('Y'),
        ]);

        // Recent orders
        $data['recent_orders'] = $this->Tailoring_order_model->getAll();
        $data['recent_orders'] = array_slice($data['recent_orders'], 0, 5);

        // Recent sales
        $data['recent_sales'] = $this->Sales_billing_model->getAll();
        $data['recent_sales'] = array_slice($data['recent_sales'], 0, 5);

        // Recent quotations
$data['recent_quotations'] = $this->Quotation_model->getAll();
$data['recent_quotations'] = array_slice($data['recent_quotations'], 0, 5);

        $this->load->view('layout/header', $data);
        $this->load->view('layout/sidebar', $data);
        $this->load->view('dashboard/index', $data);
        $this->load->view('layout/footer', $data);
    }
}