<?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
    {
        $data = $this->extractFormData($request);

        if ($data['name_ar'] === '') {
            return $this->redirect('/pricing/special-discounts/create')->withError('اسم الخصم مطلوب');
        }

        $validationError = $this->validateDiscountData($data);
        if ($validationError) {
            return $this->redirect('/pricing/special-discounts/create')->withError($validationError);
        }

        SpecialDiscount::create($this->buildCreateArray($data));

        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('الخصم غير موجود');
        }

        $data = $this->extractFormData($request);
        $data['is_active'] = (int) $request->post('is_active', 1);

        if ($data['name_ar'] === '') {
            return $this->redirect("/pricing/special-discounts/{$id}/edit")->withError('اسم الخصم مطلوب');
        }

        $validationError = $this->validateDiscountData($data);
        if ($validationError) {
            return $this->redirect("/pricing/special-discounts/{$id}/edit")->withError($validationError);
        }

        $updateArray = $this->buildCreateArray($data);
        $updateArray['is_active'] = $data['is_active'];
        $updateArray['updated_at'] = date('Y-m-d H:i:s');

        $db->update('special_discounts', $updateArray, '`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 ? 'تم تفعيل الخصم' : 'تم تعطيل الخصم');
    }

    private function extractFormData(Request $request): array
    {
        return [
            'name_ar'                      => trim((string) $request->post('name_ar', '')),
            'name_en'                      => trim((string) $request->post('name_en', '')) ?: null,
            'discount_type'                => $request->post('discount_type', 'percentage'),
            'discount_percentage'          => trim((string) $request->post('discount_percentage', '0')),
            'fixed_amount'                 => trim((string) $request->post('fixed_amount', '')) ?: null,
            'applies_to'                   => $request->post('applies_to', 'membership_fee'),
            'effective_from'               => trim((string) $request->post('effective_from', '')) ?: null,
            'effective_to'                 => trim((string) $request->post('effective_to', '')) ?: null,
            'condition_type'               => $request->post('condition_type', 'none'),
            'condition_min_amount'         => trim((string) $request->post('condition_min_amount', '')) ?: null,
            'bonus_free_subscription_years'=> (int) $request->post('bonus_free_subscription_years', 0),
            'requires_document'            => (int) $request->post('requires_document', 0),
            'description'                  => trim((string) $request->post('description', '')) ?: null,
        ];
    }

    private function validateDiscountData(array $data): ?string
    {
        $type = $data['discount_type'];

        if ($type === 'percentage') {
            $pct = $data['discount_percentage'];
            if (bccomp($pct, '0', 2) <= 0 || bccomp($pct, '100', 2) > 0) {
                return 'نسبة الخصم يجب أن تكون بين 0.01% و 100%';
            }
        } elseif ($type === 'fixed_amount') {
            if (!$data['fixed_amount'] || bccomp($data['fixed_amount'], '0', 2) <= 0) {
                return 'مبلغ الخصم الثابت مطلوب ويجب أن يكون أكبر من صفر';
            }
        }

        if ($data['condition_type'] === 'min_payment') {
            if (!$data['condition_min_amount'] || bccomp($data['condition_min_amount'], '0', 2) <= 0) {
                return 'الحد الأدنى للسداد مطلوب عند اختيار شرط "سداد حد أدنى"';
            }
        }

        $validTypes = ['percentage', 'fixed_amount', 'free_subscription'];
        if (!in_array($type, $validTypes, true)) {
            return 'نوع الخصم غير صالح';
        }

        $validAppliesTo = ['membership_fee', 'subscription', 'all'];
        if (!in_array($data['applies_to'], $validAppliesTo, true)) {
            return 'مجال التطبيق غير صالح';
        }

        $validConditions = ['none', 'full_payment', 'min_payment'];
        if (!in_array($data['condition_type'], $validConditions, true)) {
            return 'شرط التطبيق غير صالح';
        }

        if ($data['effective_from'] && $data['effective_to'] && $data['effective_from'] > $data['effective_to']) {
            return 'تاريخ البداية يجب أن يكون قبل تاريخ الانتهاء';
        }

        return null;
    }

    private function buildCreateArray(array $data): array
    {
        return [
            'name_ar'                       => $data['name_ar'],
            'name_en'                       => $data['name_en'],
            'discount_type'                 => $data['discount_type'],
            'discount_percentage'           => $data['discount_type'] === 'percentage' ? $data['discount_percentage'] : '0.00',
            'fixed_amount'                  => $data['discount_type'] === 'fixed_amount' ? $data['fixed_amount'] : null,
            'applies_to'                    => $data['applies_to'],
            'effective_from'                => $data['effective_from'],
            'effective_to'                  => $data['effective_to'],
            'condition_type'                => $data['condition_type'],
            'condition_min_amount'          => $data['condition_type'] === 'min_payment' ? $data['condition_min_amount'] : null,
            'bonus_free_subscription_years' => $data['bonus_free_subscription_years'],
            'requires_document'             => $data['requires_document'],
            'description'                   => $data['description'],
            'is_active'                     => 1,
        ];
    }
}
