<?php

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

class Coupons extends AdminController
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model(PERFEX_SAAS_MODULE_NAME . '/Perfex_saas_coupons_model', 'coupons');
    }

    public function index()
    {
        if (!has_permission('perfex_saas_coupons', '', 'view')) {
            return access_denied('perfex_saas_coupons');
        }

        $data['title'] = _l('Coupons');
        $data['coupons'] = $this->coupons->all();
        $this->load->view(PERFEX_SAAS_MODULE_NAME . '/coupons/manage', $data);
    }

    public function create()
    {
        if (!has_permission('perfex_saas_coupons', '', 'create')) {
            return access_denied('perfex_saas_coupons');
        }

        if ($this->input->post()) {
            $this->save();
            return;
        }

        $data['title'] = _l('New Coupon');
        $this->load->view(PERFEX_SAAS_MODULE_NAME . '/coupons/form', $data);
    }

    public function edit($id)
    {
        if (!has_permission('perfex_saas_coupons', '', 'edit')) {
            return access_denied('perfex_saas_coupons');
        }

        if ($this->input->post()) {
            $this->save($id);
            return;
        }

        $data['coupon'] = $this->coupons->find_by_id((int)$id);
        if (!$data['coupon']) {
            set_alert('danger', _l('No record found'));
            return redirect(admin_url(PERFEX_SAAS_MODULE_NAME . '/coupons'));
        }
        $data['title'] = _l('Edit Coupon');
        $this->load->view(PERFEX_SAAS_MODULE_NAME . '/coupons/form', $data);
    }

    private function save($id = null)
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('code', _l('Coupon code'), 'required');
        $type = $this->input->post('type', true);
        if ($type === 'fixed') {
            $this->form_validation->set_rules('amount', _l('Amount'), 'required|greater_than[0]');
        } else {
            $this->form_validation->set_rules('percent', _l('Percent'), 'required|greater_than[0]|less_than_equal_to[90]');
        }
        if ($this->form_validation->run() === false) {
            return;
        }

        $data = $this->input->post(null, true);
        $payload = [
            'code' => $data['code'] ?? '',
            'type' => in_array(($data['type'] ?? 'percent'), ['percent','fixed']) ? $data['type'] : 'percent',
            'percent' => $data['type']==='fixed' ? 0 : (int)($data['percent'] ?? 0),
            'amount' => $data['type']==='fixed' ? (float)($data['amount'] ?? 0) : 0.00,
            'starts_at' => !empty($data['starts_at']) ? $data['starts_at'] : null,
            'ends_at' => !empty($data['ends_at']) ? $data['ends_at'] : null,
            'max_uses' => (int)($data['max_uses'] ?? 0),
            'status' => ($data['status'] ?? 'inactive') === 'active' ? 'active' : 'inactive',
        ];

        try {
            if ($id) {
                $ok = $this->coupons->update((int)$id, $payload);
                if ($ok) set_alert('success', _l('updated_successfully', _l('Coupon')));
            } else {
                $cid = $this->coupons->create($payload);
                if ($cid) set_alert('success', _l('added_successfully', _l('Coupon')));
            }
        } catch (\Throwable $th) {
            set_alert('danger', $th->getMessage());
        }

        return redirect(admin_url(PERFEX_SAAS_MODULE_NAME . '/coupons'));
    }

    public function delete()
    {
        if (!has_permission('perfex_saas_coupons', '', 'delete')) {
            return access_denied('perfex_saas_coupons');
        }
        $id = (int)$this->input->post('id', true);
        if ($id) {
            $this->coupons->delete($id);
            set_alert('success', _l('deleted', _l('Coupon')));
        }
        return redirect(admin_url(PERFEX_SAAS_MODULE_NAME . '/coupons'));
    }

    public function toggle($id)
    {
        if (!has_permission('perfex_saas_coupons', '', 'edit')) {
            return access_denied('perfex_saas_coupons');
        }
        $coupon = $this->coupons->find_by_id((int)$id);
        if ($coupon) {
            $new = $coupon->status === 'active' ? 'inactive' : 'active';
            $this->coupons->toggle_status((int)$id, $new);
        }
        return redirect(admin_url(PERFEX_SAAS_MODULE_NAME . '/coupons'));
    }
}
