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

class Coupon_logs extends AdminController
{
    public function __construct()
    {
        parent::__construct();
        if (!has_permission('perfex_saas_coupon_logs', '', 'view')) {
            access_denied();
        }
        $this->load->model('perfex_saas/Perfex_saas_coupon_logs_model', 'coupon_logs');
    }

    public function index()
    {
        $filters = [
            'code' => $this->input->get('code', true),
            'from' => $this->input->get('from', true),
            'to'   => $this->input->get('to', true),
        ];
        $logs = $this->coupon_logs->get_logs($filters);
        $aggregate = $this->coupon_logs->aggregate();

        if($this->input->get('export') === 'csv'){
            $filename = 'coupon_logs_' . date('Ymd_His') . '.csv';
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment; filename="'.$filename.'"');
            $out = fopen('php://output','w');
            fputcsv($out, ['ID','CODE','DISCOUNT TYPE','VALUE','INVOICE','IP','DATE']);
            foreach($logs as $l){
                fputcsv($out, [$l->id,$l->code_snapshot,$l->discount_type,$l->discount_value,$l->invoice_id,$l->ip_address,$l->created_at]);
            }
            fclose($out);exit;
        }

        $data = compact('logs','aggregate','filters');
        $this->load->view('perfex_saas/coupon_logs/manage', $data);
    }
}
