<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Custom_report extends REF_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library('upload');
        $this->load->model('reports/custom_report_model', '', TRUE);
        $this->load->model('reports/daily_summary_model', '', TRUE);
        $this->load->model('general_settings_model', '', TRUE);
        $this->uri_key_index = 0;
    }

    public function index() {
        $data = array();

        if (!empty($this->session->flashdata('success')))
            $data['success'] = $this->session->flashdata('success');
        else
            $data['error'] = $this->session->flashdata('error');

        $submit = $this->input->post('submit');
        $searched = (!empty($submit) && in_array($submit, array('Search', 'Print Data', 'Excel Data', 'PDF Data')));

        if( $searched ) {
            $from_date    = $this->input->post('from_date');
            $to_date      = $this->input->post('to_date');
            $category_id  = $this->input->post('category_id');
            $sub_category = $this->input->post('sub_category');
        } else {
            $from_date    = date('d-m-Y');
            $to_date      = date('d-m-Y');
            $category_id  = '';
            $sub_category = '';
        }

        $general = $this->general_settings_model->get_by_id();

        $data['results']         = $this->get_receipts($from_date, $to_date, $category_id, $sub_category, $general);
        $data['payment_summary'] = $this->summarize_by_payment_type($data['results']);
        $data['from_date']    = $from_date;
        $data['to_date']      = $to_date;
        $data['category_id']  = $category_id;
        $data['sub_category'] = $sub_category;
        $data['categories']   = $this->custom_report_model->category_list();
        $data['sub_lists']    = $this->custom_report_model->sub_category_lists();
        $data['general']      = $general;
        $data['searched']     = $searched;
        $data['form_action']  = 'custom_report';
        $data['title']        = 'Custom Report';

        $filters = array();
        if(!empty($this->input->post('filter_columns'))) {
            foreach($this->input->post('filter_columns') as $key=>$value) {
                array_push($filters, $this->input->post($value));
            }
        }
        $data['filters'] = array_filter($filters);

        if($submit == 'Print Data') {
            if( IS_KSK ) :
                $html = $this->load->view('reports/custom_report/pdf', $data, TRUE);
                print_rec($html);
                redirect('custom_report','refresh');
            else :
                $this->render($data, 'reports/custom_report/pdf');
            endif;
        } elseif($submit == 'PDF Data') {
            $this->download_pdf($data);
        } elseif($submit == 'Excel Data') {
            $this->load->view('reports/custom_report/excel', $data);
        } else {
            $this->render($data, 'reports/custom_report/list');
        }
    }

    /*
     * Pulls "Get Details Data" (one row per receipt) from the relevant
     * Daily_summary_model getter(s), one calendar day at a time across the
     * requested range, then reshapes each row for display.
     */
    private function get_receipts($from_date, $to_date, $category_id, $sub_category, $general) {
        if(empty($from_date) || empty($to_date)) return array();

        $start = strtotime($from_date);
        $end   = strtotime($to_date);
        if($start === FALSE || $end === FALSE || $start > $end) return array();

        $method_map = $this->custom_report_model->category_method_map();
        $methods = (!empty($category_id) && isset($method_map[$category_id]))
            ? array($category_id => $method_map[$category_id])
            : $method_map;

        $rows = array();

        for($ts = $start; $ts <= $end; $ts = strtotime('+1 day', $ts)) {
            $day = date('d-m-Y', $ts);
            $refund_map = $this->daily_summary_model->get_refund_amounts_map($day);

            foreach($methods as $method) {
                $day_rows = $this->daily_summary_model->$method($day, 'Get Details Data');

                foreach($day_rows as $row) {
                    if(!empty($sub_category) && (empty($row['name']) || $row['name'] !== $sub_category)) continue;

                    $rows[] = $this->build_row($row, $day, $general, $refund_map);
                }
            }
        }

        return $rows;
    }

    private function build_row($row, $day, $general, $refund_map) {
        $amount = !empty($row['amount']) ? $row['amount'] : 0;

        // Net out refunds the same way Daily Summary Report does, so the two
        // reports agree on Before GST / GST Amount / Total for the same receipts.
        $refund_key = $row['type_id'] . '_' . $row['service_id'] . '_' . $row['id'];
        $refund = isset($refund_map[$refund_key]) ? $refund_map[$refund_key] : 0;
        $recent_amt = !empty($refund) ? $amount - $refund : $amount;

        $has_qty_price = isset($row['qty']) && isset($row['price']);
        $qty   = $has_qty_price ? $row['qty'] : 1;
        $price = $has_qty_price ? $row['price'] : $amount;

        if(!empty($row['gst']) && $row['gst'] > 0) {
            $before_gst = (($recent_amt / 109) * 100);
            $gst_amount = $recent_amt - $before_gst;
        } else {
            $before_gst = $recent_amt;
            $gst_amount = 0;
        }

        $gst_type = ($general->gst > 0 && !empty($row['is_gst']) && $row['is_gst'] != 0) ? 'Yes' : 'No';

        $mem_card_id = !empty($row['mem_card_id']) ? $row['mem_card_id'] : '';
        $payment = $this->daily_summary_model->get_payment_details($row['type_id'], $row['id'], $day, $mem_card_id);
        $payment_type = !empty($payment[0]['payment']) ? $payment[0]['payment'] : '-';

        return array(
            'rec_no'       => $row['rec_no'],
            'date'         => date('d-m-Y', strtotime($day)),
            'cat_name'     => $row['cat_name'],
            'name'         => $row['name'],
            'payment_type' => $payment_type,
            'gst_type'     => $gst_type,
            'qty'          => $qty,
            'price'        => number_format($price, 2, '.', ''),
            'before_gst'   => number_format($before_gst, 2, '.', ''),
            'gst_amount'   => number_format($gst_amount, 2, '.', ''),
            'total'        => number_format($recent_amt, 2, '.', ''),
        );
    }

    // Totals the displayed receipts by their Payment Type, e.g. Cash S$1,200, NETS S$450
    private function summarize_by_payment_type($rows) {
        $summary = array();

        foreach($rows as $row) {
            $key = !empty($row['payment_type']) ? $row['payment_type'] : '-';
            if(!isset($summary[$key])) $summary[$key] = 0;
            $summary[$key] += (float) $row['total'];
        }

        ksort($summary);
        return $summary;
    }

    private function download_pdf($data) {
        $html = $this->load->view('reports/custom_report/pdf', $data, TRUE);
        $this->load->library('m_pdf');
        $pdf = $this->m_pdf->load();
        $pdf->SetAutoFont(AUTOFONT_ALL);
        $pdf->AddPage('L', '', '', '', '', 5, 5, 5, 5, 3, 3);
        $pdf->setFooter('{PAGENO}');
        $pdf->WriteHTML($html);
        $pdf->Output('custom_report_' . date('Y-m-d') . '.pdf', 'D');
        exit;
    }
}
