<?php
declare(strict_types=1);

namespace App\Modules\Pricing\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Pricing\Models\SpecialDiscount;

class SpecialDiscountController extends Controller
{
    public function index(Request $request): Response
    {
        $filters = [
            'search'    => trim((string) $request->get('q', '')),
            'is_active' => $request->get('is_active', ''),
        ];
        $page = max(1, (int) $request->get('page', 1));
        $result = SpecialDiscount::search($filters, 25, $page);

        return $this->view('Pricing.Views.special_discounts.index', [
            'rows'       => $result['data'],
            'pagination' => $result['pagination'],
            'filters'    => $filters,
        ]);
    }

    public function create(Request $request): Response
    {
        return $this->view('Pricing.Views.special_discounts.form', [
            'discount' => null,
        ]);
    }

    public function store(Request $request): Response
    {
        $nameAr = trim((string) $request->post('name_ar', ''));
        $nameEn = trim((string) $request->post('name_en', '')) ?: null;
        $percentage = trim((string) $request->post('discount_percentage', '0'));
        $requiresDocument = (int) $request->post('requires_document', 0);
        $description = trim((string) $request->post('description', '')) ?: null;

        if ($nameAr === '') {
            return $this->redirect('/pricing/special-discounts/create')->withError('اسم الخصم مطلوب');
        }
        if (bccomp($percentage, '0', 2) <= 0 || bccomp($percentage, '100', 2) > 0) {
            return $this->redirect('/pricing/special-discounts/create')->withError('نسبة الخصم يجب أن تكون بين 0.01% و 100%');
        }

        $employee = App::getInstance()->currentEmployee();

        SpecialDiscount::create([
            'name_ar'             => $nameAr,
            'name_en'             => $nameEn,
            'discount_percentage' => $percentage,
            'requires_document'   => $requiresDocument,
            'description'         => $description,
            'is_active'           => 1,
        ]);

        return $this->redirect('/pricing/special-discounts')->withSuccess('تم إضافة الخصم الخاص بنجاح');
    }

    public function edit(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();
        $discount = $db->selectOne("SELECT * FROM `special_discounts` WHERE `id` = ?", [(int) $id]);
        if (!$discount) {
            return $this->redirect('/pricing/special-discounts')->withError('الخصم غير موجود');
        }

        return $this->view('Pricing.Views.special_discounts.form', [
            'discount' => $discount,
        ]);
    }

    public function update(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();
        $discount = $db->selectOne("SELECT * FROM `special_discounts` WHERE `id` = ?", [(int) $id]);
        if (!$discount) {
            return $this->redirect('/pricing/special-discounts')->withError('الخصم غير موجود');
        }

        $nameAr = trim((string) $request->post('name_ar', ''));
        $nameEn = trim((string) $request->post('name_en', '')) ?: null;
        $percentage = trim((string) $request->post('discount_percentage', '0'));
        $requiresDocument = (int) $request->post('requires_document', 0);
        $description = trim((string) $request->post('description', '')) ?: null;
        $isActive = (int) $request->post('is_active', 1);

        if ($nameAr === '') {
            return $this->redirect("/pricing/special-discounts/{$id}/edit")->withError('اسم الخصم مطلوب');
        }
        if (bccomp($percentage, '0', 2) <= 0 || bccomp($percentage, '100', 2) > 0) {
            return $this->redirect("/pricing/special-discounts/{$id}/edit")->withError('نسبة الخصم يجب أن تكون بين 0.01% و 100%');
        }

        $db->update('special_discounts', [
            'name_ar'             => $nameAr,
            'name_en'             => $nameEn,
            'discount_percentage' => $percentage,
            'requires_document'   => $requiresDocument,
            'description'         => $description,
            'is_active'           => $isActive,
            'updated_at'          => date('Y-m-d H:i:s'),
        ], '`id` = ?', [(int) $id]);

        return $this->redirect('/pricing/special-discounts')->withSuccess('تم تحديث الخصم الخاص');
    }

    public function toggleActive(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();
        $discount = $db->selectOne("SELECT * FROM `special_discounts` WHERE `id` = ?", [(int) $id]);
        if (!$discount) {
            return $this->redirect('/pricing/special-discounts')->withError('الخصم غير موجود');
        }

        $newActive = $discount['is_active'] ? 0 : 1;
        $db->update('special_discounts', [
            'is_active'  => $newActive,
            'updated_at' => date('Y-m-d H:i:s'),
        ], '`id` = ?', [(int) $id]);

        return $this->redirect('/pricing/special-discounts')->withSuccess($newActive ? 'تم تفعيل الخصم' : 'تم تعطيل الخصم');
    }
}
