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

class Issuance_Controller extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('Issuance_model');
        $this->load->helper(array('url', 'form'));
        $this->load->library('form_validation');
    }

    /**
     * Default page – show search form
     */
    public function index()
    {
        $data = [
            'view'      => 'IssuanceReportSearch.php',
            'results'   => '',
            'fromDate'  => '',
            'toDate'    => ''
        ];

        $this->load->view('master', $data);
    }

    /**
     * Handle search form POST
     */
    public function search()
    {
        if (!$this->input->post()) {
            redirect('IssuanceReport/Issuance_Controller');
            return;
        }

        $fromDate  = $this->input->post('fromDate');
        $toDate    = $this->input->post('toDate');

        // Get results from model
        $results = [];
        if (!empty($fromDate) && !empty($toDate)) {
            $results = $this->Issuance_model->searchDetails($fromDate, $toDate);
        }

        $data = [
            'results'   => $results,
            'fromDate'  => $fromDate,
            'toDate'    => $toDate,
            'view'      => 'IssuanceReportSearch.php'
        ];

        $this->load->view('master', $data);
    }

    /**
     * Export to CSV
     */
    public function exportCsv()
    {
        $fromDate  = $this->input->get('fromDate');
        $toDate    = $this->input->get('toDate');

        if (!empty($fromDate) && !empty($toDate)) {
            $query = $this->Issuance_model->searchDetails($fromDate, $toDate);
        } else {
            $query = [];
        }

        // Month/Year for filename
        $monthYear = '';
        if (!empty($fromDate)) {
            $monthYear = strtoupper(date('F_Y', strtotime($fromDate)));
        }

        $fromDateFormatted = !empty($fromDate) ? date('d/m/Y', strtotime($fromDate)) : '';
        $toDateFormatted   = !empty($toDate)   ? date('d/m/Y', strtotime($toDate))   : '';

        // Set CSV headers
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="IssuanceNoteReport_'.$monthYear.'.csv"');
        header('Pragma: no-cache');
        header('Expires: 0');

        $output = fopen('php://output', 'w');

        // BOM for Excel UTF-8 compatibility
        fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));

        // Title row
        fputcsv($output, ['ISSUANCE NOTE AL DANA INTERNATIONAL CO  From '.$fromDateFormatted.' To '.$toDateFormatted]);

        // Empty row
        fputcsv($output, []);

        // Column headers
        fputcsv($output, ['DATE', 'ITEM NAME', 'JOB CARD NO', 'QTY', 'UNIT PRICE', 'COST']);

        // Data rows
        $totalCost = 0;

        if (!empty($query)) {
            foreach ($query as $row) {
                $cost = $row->amount;
                $totalCost += $cost;

                fputcsv($output, [
                    date("d/m/Y", strtotime($row->issue_date)),
                    $row->description,
                    $row->job_card_no,
                    $row->quantity,
                    number_format($row->unit_price, 2),
                    number_format($cost, 2)
                ]);
            }

            // Total row
            fputcsv($output, ['', '', '', '', 'TOTAL', number_format($totalCost, 2)]);
        } else {
            fputcsv($output, ['No Data Available']);
        }

        fclose($output);
        exit;
    }
}
