<?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\BoardOffer;

class BoardOfferController 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 = BoardOffer::search($filters, 25, $page);

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

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

    public function store(Request $request): Response
    {
        $data = $this->extractFormData($request);

        $error = $this->validateOfferData($data);
        if ($error) {
            $session = App::getInstance()->session();
            $session->flash('_old_input', $data);
            return $this->redirect('/pricing/board-offers/create')->withError($error);
        }

        $employee = App::getInstance()->currentEmployee();
        $data['created_by'] = $employee ? (int) $employee->id : null;

        BoardOffer::create($data);

        return $this->redirect('/pricing/board-offers')->withSuccess('تم إضافة عرض مجلس الإدارة بنجاح');
    }

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

        $branches = $this->getBranches();
        return $this->view('Pricing.Views.board_offers.form', [
            'offer'    => $offer,
            'branches' => $branches,
        ]);
    }

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

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

        $error = $this->validateOfferData($data);
        if ($error) {
            $session = App::getInstance()->session();
            $session->flash('_old_input', $data);
            return $this->redirect("/pricing/board-offers/{$id}/edit")->withError($error);
        }

        $employee = App::getInstance()->currentEmployee();
        $data['updated_by'] = $employee ? (int) $employee->id : null;
        $data['updated_at'] = date('Y-m-d H:i:s');

        $db->update('board_offers', $data, '`id` = ?', [(int) $id]);

        return $this->redirect('/pricing/board-offers')->withSuccess('تم تحديث العرض بنجاح');
    }

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

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

        return $this->redirect('/pricing/board-offers')->withSuccess($newActive ? 'تم تفعيل العرض' : 'تم تعطيل العرض');
    }

    private function extractFormData(Request $request): array
    {
        $hasCash = (int) $request->post('has_cash_path', 0);
        $hasInst = (int) $request->post('has_inst_path', 0);

        return [
            'title_ar'              => trim((string) $request->post('title_ar', '')),
            'title_en'              => trim((string) $request->post('title_en', '')) ?: null,
            'description'           => trim((string) $request->post('description', '')) ?: null,
            'cash_discount_type'    => $hasCash ? ($request->post('cash_discount_type', null) ?: null) : null,
            'cash_discount_value'   => $hasCash ? (trim((string) $request->post('cash_discount_value', '')) ?: null) : null,
            'inst_down_payment_pct' => $hasInst ? (trim((string) $request->post('inst_down_payment_pct', '')) ?: null) : null,
            'inst_months'           => $hasInst ? ((int) $request->post('inst_months', 0) ?: null) : null,
            'inst_interest_rate'    => $hasInst ? (trim((string) $request->post('inst_interest_rate', '')) !== '' ? trim((string) $request->post('inst_interest_rate', '')) : null) : null,
            'inst_grace_type'       => $hasInst ? ($request->post('inst_grace_type', '') ?: null) : null,
            'inst_grace_months'     => $hasInst ? (int) $request->post('inst_grace_months', 0) : 0,
            'inst_post_grace_rate'  => $hasInst ? (trim((string) $request->post('inst_post_grace_rate', '')) ?: null) : null,
            'branch_id'             => ((int) $request->post('branch_id', 0)) ?: null,
            'applies_to'            => $request->post('applies_to', 'membership_fee'),
            'effective_from'        => trim((string) $request->post('effective_from', '')),
            'effective_to'          => trim((string) $request->post('effective_to', '')),
            'is_active'             => 1,
            'board_decision_number' => trim((string) $request->post('board_decision_number', '')) ?: null,
            'board_decision_date'   => trim((string) $request->post('board_decision_date', '')) ?: null,
            'notes'                 => trim((string) $request->post('notes', '')) ?: null,
        ];
    }

    private function validateOfferData(array $data): ?string
    {
        if ($data['title_ar'] === '') {
            return 'عنوان العرض بالعربي مطلوب';
        }

        if (empty($data['effective_from']) || empty($data['effective_to'])) {
            return 'تاريخ البداية والانتهاء مطلوبان';
        }

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

        $hasCash = ($data['cash_discount_type'] !== null);
        $hasInst = ($data['inst_months'] !== null || $data['inst_interest_rate'] !== null || $data['inst_down_payment_pct'] !== null || $data['inst_grace_type'] !== null);

        if (!$hasCash && !$hasInst) {
            return 'يجب تحديد مسار واحد على الأقل (كاش أو تقسيط)';
        }

        if ($hasCash) {
            if (!in_array($data['cash_discount_type'], ['percentage', 'fixed_amount'], true)) {
                return 'نوع خصم الكاش غير صالح';
            }
            $val = (float) ($data['cash_discount_value'] ?? 0);
            if ($val <= 0) {
                return 'قيمة خصم الكاش يجب أن تكون أكبر من صفر';
            }
            if ($data['cash_discount_type'] === 'percentage' && $val > 100) {
                return 'نسبة خصم الكاش لا يمكن أن تتجاوز 100%';
            }
        }

        if ($hasInst) {
            if ($data['inst_down_payment_pct'] !== null) {
                $dp = (float) $data['inst_down_payment_pct'];
                if ($dp < 0 || $dp > 100) {
                    return 'نسبة المقدم يجب أن تكون بين 0 و 100';
                }
            }
            if ($data['inst_interest_rate'] !== null) {
                $ir = (float) $data['inst_interest_rate'];
                if ($ir < 0 || $ir > 100) {
                    return 'نسبة الفائدة يجب أن تكون بين 0 و 100';
                }
            }
            if ($data['inst_grace_type'] !== null) {
                if (!in_array($data['inst_grace_type'], ['first_n_months', 'full_free_under_n'], true)) {
                    return 'نوع فترة السماح غير صالح';
                }
                if ($data['inst_grace_months'] < 1) {
                    return 'عدد أشهر السماح يجب أن يكون 1 على الأقل';
                }
                if ($data['inst_grace_type'] === 'first_n_months' && $data['inst_months'] !== null && $data['inst_grace_months'] >= (int) $data['inst_months']) {
                    return 'أشهر السماح يجب أن تكون أقل من إجمالي عدد الأقساط';
                }
            }
        }

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

        return null;
    }

    private function getBranches(): array
    {
        $db = App::getInstance()->db();
        return $db->select("SELECT `id`, `name_ar` FROM `branches` WHERE `is_active` = 1 ORDER BY `name_ar`");
    }
}
