<?php
declare(strict_types=1);

namespace App\Modules\Seasonal\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Core\EventBus;
use App\Modules\Seasonal\Models\SeasonalMembership;
use App\Modules\Rules\Services\RuleEngine;
use App\Modules\Payments\Services\PaymentService;
use App\Modules\Cashier\Services\PaymentRequestService;

class SeasonalController extends Controller
{
    public function index(Request $request): Response
    {
        $db = App::getInstance()->db();
        $status = $request->get('status', '');

        $where = 's.is_archived = 0';
        $params = [];
        if ($status !== '') {
            $where .= ' AND s.status = ?';
            $params[] = $status;
        }

        $rows = $db->select(
            "SELECT s.*, m.full_name_ar as member_name, m.membership_number, b.name_ar as branch_name
             FROM seasonal_memberships s
             JOIN members m ON m.id = s.member_id
             JOIN branches b ON b.id = s.branch_id
             WHERE {$where}
             ORDER BY s.created_at DESC LIMIT 100",
            $params
        );

        return $this->view('Seasonal.Views.index', ['rows' => $rows, 'status' => $status]);
    }

    public function create(Request $request, string $memberId): Response
    {
        $db = App::getInstance()->db();
        $member = $db->selectOne("SELECT * FROM members WHERE id = ? AND is_archived = 0", [(int) $memberId]);
        if (!$member) {
            return $this->redirect('/members')->withError('العضو غير موجود');
        }

        $branches = $db->select("SELECT id, name_ar FROM branches WHERE is_active = 1 ORDER BY name_ar");
        $membershipValue = $member['membership_value'] ?? '0.00';

        $feeData = RuleEngine::get('SEASONAL_FEE');
        $pct = $feeData['percentage'] ?? '5.00';
        $fee = bcmul($membershipValue, bcdiv($pct, '100', 4), 2);

        $maxMonthsData = RuleEngine::get('SEASONAL_MAX_MONTHS');
        $maxMonths = $maxMonthsData['months'] ?? 6;

        return $this->view('Seasonal.Views.create', [
            'member'    => $member,
            'branches'  => $branches,
            'fee'       => $fee,
            'pct'       => $pct,
            'maxMonths' => $maxMonths,
        ]);
    }

    public function store(Request $request, string $memberId): Response
    {
        $db = App::getInstance()->db();
        $member = $db->selectOne("SELECT * FROM members WHERE id = ? AND is_archived = 0", [(int) $memberId]);
        if (!$member) {
            return $this->redirect('/members')->withError('العضو غير موجود');
        }

        $data = $request->all();
        unset($data['_csrf_token']);

        $errors = [];
        if (empty($data['branch_id'] ?? '')) $errors[] = 'الفرع مطلوب';
        if (empty($data['start_date'] ?? '')) $errors[] = 'تاريخ البداية مطلوب';

        $maxMonthsData = RuleEngine::get('SEASONAL_MAX_MONTHS');
        $maxMonths = $maxMonthsData['months'] ?? 6;

        $startDate = $data['start_date'] ?? date('Y-m-d');
        $endDate = date('Y-m-d', strtotime($startDate . " +{$maxMonths} months"));

        $membershipValue = $member['membership_value'] ?? '0.00';
        $feeData = RuleEngine::get('SEASONAL_FEE');
        $pct = $feeData['percentage'] ?? '5.00';
        $fee = bcmul($membershipValue, bcdiv($pct, '100', 4), 2);

        if (!empty($errors)) {
            $session = App::getInstance()->session();
            $session->flash('_alerts', array_map(fn($e) => ['type' => 'error', 'message' => $e], $errors));
            $session->flash('_old_input', $data);
            return $this->redirect("/members/{$memberId}/seasonal/create");
        }

        $hasFee = bccomp($fee, '0.00', 2) > 0;
        $seasonal = SeasonalMembership::create([
            'member_id'          => (int) $memberId,
            'branch_id'          => (int) $data['branch_id'],
            'start_date'         => $startDate,
            'end_date'           => $endDate,
            'fee_amount'         => $fee,
            'status'             => $hasFee ? 'pending_payment' : 'active',
            'carnet_marking'     => 'موسمي',
            'notes'              => $data['notes'] ?? null,
        ]);

        if ($hasFee) {
            $payResult = PaymentRequestService::createRequest([
                'member_id'           => (int) $memberId,
                'amount'              => $fee,
                'payment_type'        => 'seasonal_fee',
                'related_entity_type' => 'seasonal_memberships',
                'related_entity_id'   => (int) $seasonal->id,
                'description_ar'      => 'رسوم عضوية موسمية — من ' . $startDate . ' إلى ' . $endDate,
            ]);

            if (!$payResult['success']) {
                return $this->redirect("/members/{$memberId}/seasonal/create")
                    ->withError('تم إنشاء العضوية الموسمية لكن فشل إنشاء طلب الدفع: ' . ($payResult['error'] ?? ''));
            }
        }

        EventBus::dispatch('seasonal.created', [
            'member_id'   => (int) $memberId,
            'seasonal_id' => (int) $seasonal->id,
            'fee'         => $fee,
        ]);

        return $this->redirect("/members/{$memberId}")
            ->withSuccess("تم إنشاء العضوية الموسمية وإرسال طلب الدفع للخزينة — من {$startDate} إلى {$endDate} — الرسوم: " . money($fee));
    }
}