<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Helpers\ActivityLogger;
use App\Models\SettingsModel;
use Core\Request;
use Core\Session;

/**
 * Store-wide discount policies:
 *   - General order discount (% or fixed on every order)
 *   - First-order discount (applied automatically to a customer's first order)
 * Stored in the key/value `settings` table.
 */
final class DiscountPolicyController extends BaseController
{
    private SettingsModel $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = new SettingsModel();
    }

    public function index(array $params = []): void
    {
        $this->requirePermission('settings.manage');
        $this->view('discount_policies.index', [
            'pageTitle'   => 'Discount Policies',
            'breadcrumbs' => ['Discount Policies' => null],
            'settings'    => $this->model->all(),
        ]);
    }

    public function update(array $params = []): void
    {
        $this->requirePermission('settings.manage');
        Request::verifyCsrf();

        $type = fn(string $k) => in_array(Request::str($k), ['percentage', 'fixed'])
            ? Request::str($k) : 'percentage';
        $num  = fn(string $k) => (string) max(0, (float) Request::str($k, '0'));

        $this->model->bulkSet([
            // General order discount (applies to every order)
            'order_discount_enabled'    => Request::str('order_discount_enabled') === '1' ? '1' : '0',
            'order_discount_type'       => $type('order_discount_type'),
            'order_discount_value'      => $num('order_discount_value'),
            'order_discount_min_amount' => $num('order_discount_min_amount'),
            'order_discount_max_discount' => $num('order_discount_max_discount'),
            // First-order discount
            'first_order_discount_enabled' => Request::str('first_order_discount_enabled') === '1' ? '1' : '0',
            'first_order_discount_type'    => $type('first_order_discount_type'),
            'first_order_discount_value'   => $num('first_order_discount_value'),
            'first_order_min_amount'       => $num('first_order_min_amount'),
            'first_order_max_discount'     => $num('first_order_max_discount'),
        ]);
        SettingsModel::clearCache();

        ActivityLogger::updated('Discount Policies', 0, 'discount policies');
        Session::flash('success', 'Discount policies saved successfully.');
        $this->redirect('/discount-policies');
    }
}
