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

// Manually require the autoload file from the library's directory
require_once APPPATH . 'third_party/escpos/autoload.php';

use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
use Mike42\Escpos\PrintConnectors\NetworkPrintConnector;

class Reporting extends CI_Controller {

    private $printerName = "Black Copper BC-85AC"; // printer name

    public function __construct()
    {


        parent::__construct();



    // Get the called method
    $current_method = $this->router->fetch_method();

    // List of methods that can bypass session
    $public_methods = ['bill_print_view'];

    if (!in_array($current_method, $public_methods)) {
        if (!isset($_SESSION['qurbani_user_id'])) {
            redirect('/admin', 'refresh');
        }
    }

        // Load all required models
        $this->load->model('User_model', 'user');
        $this->load->model('Settings_model', 'setup');
        $this->load->model('Payment_model', 'payment');
        $this->load->model('Token_model', 'token');
        $this->load->model('Shifts_model', 'shifts');
        $this->load->model('Departments_model', 'departments');
        $this->load->model('Services_model', 'services');
        $this->load->model('Sub_services_model', 'sub_services');
        $this->load->model('Slip_settings_model', 'slipsetup');

        $this->load->model('Reporting_model', 'report');


        $this->load->helper('custom');

    }



public function tokens()
    {
        if (!$this->user->has_permission('tokens', 'view')) {
            redirect('/admin', 'refresh');
        }

        // -------------------------
        // DATE FILTER
        // -------------------------
        $from = $this->input->get('from_date') ?: date('Y-m-d');
        $to   = $this->input->get('to_date')   ?: date('Y-m-d');

        $data['from_date'] = $from;
        $data['to_date']   = $to;

        // -------------------------
        // SHIFTS DATA
        // -------------------------
        $data['shifts'] = $this->shifts->get_all();

        // -------------------------
        // REPORT DATA FROM MODEL
        // -------------------------
        $stats = $this->report->departmentStats($from, $to);

        // -------------------------
        // GLOBAL TOTALS
        // -------------------------
$totalTokens       = 0;
$totalAmount       = 0;
$totalFundedTokens = 0;
$totalFundedAmount = 0;
$totalDiscount     = 0;
$totalRefund       = 0;
$totalDueAmount    = 0;

foreach ($stats as $dept) {
    foreach ($dept['sponsors'] as $sp) {
        // ALL TOKENS (including self/walk-in)
        $totalTokens   += $sp['total_tokens'];
        $totalAmount   += $sp['total_amount'];
        $totalDiscount += $sp['total_discount'];
        $totalRefund   += $sp['total_refund'];
        $totalDueAmount += $sp['due_amount'];

        // ONLY FUNDED TOKENS (exclude walk-ins/self)
        if ($sp['funded_by'] !== '') {
            $totalFundedTokens += $sp['total_tokens'];
            $totalFundedAmount += $sp['net_total'];
        }
    }
}
// -------------------------
// DEPT + SHIFT NET AMOUNT
// -------------------------
$deptShiftNet = [];
$shiftNames   = [];

foreach ($data['shifts'] as $shift) {
    $shiftNames[$shift->id] = $shift->name;
}

foreach ($stats as $dept) {
    $deptName = $dept['department_name'];

    if (!isset($deptShiftNet[$deptName])) {
        $deptShiftNet[$deptName] = [];
    }

    foreach ($data['shifts'] as $shift) {
        $deptShiftNet[$deptName][$shift->id] = 0;
    }

    foreach ($dept['sponsors'] as $sp) {
        foreach ($sp['shifts'] as $shiftId => $count) {

            // yahan amount split karna hai
            // approx formula: net_total / total_tokens * shift_tokens
            if ($sp['total_tokens'] > 0) {
                $perToken = $sp['net_total'] / $sp['total_tokens'];
                $deptShiftNet[$deptName][$shiftId] += ($perToken * $count);
            }
        }
    }
}

$data['deptShiftNet'] = $deptShiftNet;
$data['shiftNames']   = $shiftNames;
// -------------------------
// SHIFT WISE CHART DATA
// -------------------------
$shiftChartLabels = [];
$shiftChartData   = [];

// shift names labels
foreach ($data['shifts'] as $shift) {
    $shiftChartLabels[$shift->id] = $shift->name;
    $shiftChartData[$shift->id]   = 0;
}

// total tokens per shift
foreach ($stats as $dept) {
    foreach ($dept['sponsors'] as $sp) {
        foreach ($sp['shifts'] as $shiftId => $count) {
            if (!isset($shiftChartData[$shiftId])) {
                $shiftChartData[$shiftId] = 0;
            }
            $shiftChartData[$shiftId] += $count;
        }
    }
}

$data['shiftChartLabels'] = array_values($shiftChartLabels);
$data['shiftChartData']   = array_values($shiftChartData);

        // -------------------------
        // CHART DATA
        // -------------------------
        $deptChartLabels = [];
        $deptTokenData   = [];
        $deptNetData     = [];

        foreach ($stats as $dept) {
            $deptTokens = 0;
            $deptNet    = 0;

            foreach ($dept['sponsors'] as $sp) {
                $deptTokens += $sp['total_tokens'];
                $deptNet    += $sp['net_total'];
            }

            $deptChartLabels[] = $dept['department_name'];
            $deptTokenData[]   = $deptTokens;
            $deptNetData[]     = $deptNet;
        }

        // -------------------------
        // NET CASH (FINAL FORMULA)
        // -------------------------
        $totalCash = $totalAmount - $totalDueAmount;
            // - $totalDiscount
            // - $totalRefund
            // - $totalFundedAmount
            // - $totalDueAmount

       	$grossTotal = $totalAmount
            + $totalDiscount
            + $totalRefund
            // - $totalFundedAmount
            // - $totalDueAmount
            ;

        // -------------------------
        // PASS DATA TO VIEW
        // -------------------------
        $data['stats']             = $stats;
        $data['totalTokens']       = $totalTokens;
        $data['totalAmount']       = $totalAmount;
        $data['totalDiscount']     = $totalDiscount;
        $data['totalRefund']       = $totalRefund;
        $data['totalDueAmount']    = $totalDueAmount;
        $data['totalFundedAmount'] = $totalFundedAmount;
        $data['totalFundedTokens'] = $totalFundedTokens;
        $data['totalCash']         = $totalCash;
        $data['grossTotal']        = $grossTotal;

        $data['deptChartLabels'] = $deptChartLabels;
        $data['deptTokenData']   = $deptTokenData;
        $data['deptNetData']     = $deptNetData;

        $data['title']       = 'Token Reporting';
        $data['mainContent'] = 'admin/reporting/tokens';
$data['settings'] = $this->setup->get_by_id(1);
        $this->load->view('admin/layout/master', $data);
    }




}