<?php
declare(strict_types=1);

namespace App\Modules\Honorary\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Core\EventBus;
use App\Modules\Honorary\Models\HonoraryMember;
use App\Modules\Rules\Services\RuleEngine;

class HonoraryController extends Controller
{
    public function index(Request $request): Response
    {
        $rows = HonoraryMember::getAllActive();
        return $this->view('Honorary.Views.index', ['rows' => $rows]);
    }

    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('العضو غير موجود');
        if (($member['membership_type'] ?? 'working') !== 'honorary') {
            return $this->redirect("/members/{$memberId}")->withError('هذا العضو ليس عضواً شرفياً');
        }

        $existing = $db->selectOne("SELECT id FROM honorary_members WHERE member_id = ? AND is_archived = 0 LIMIT 1", [(int) $memberId]);
        if ($existing) return $this->redirect("/members/{$memberId}")->withError('العضوية الشرفية مسجلة بالفعل');

        $durationData = RuleEngine::get('HONORARY_DURATION_YEARS');
        $years = $durationData['years'] ?? 1;

        return $this->view('Honorary.Views.create', ['member' => $member, 'duration_years' => $years]);
    }

    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('العضو غير موجود');
        if (($member['membership_type'] ?? 'working') !== 'honorary') {
            return $this->redirect("/members/{$memberId}")->withError('هذا العضو ليس عضواً شرفياً');
        }

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

        $reason = trim($data['reason'] ?? '');
        if ($reason === '') {
            return $this->redirect("/members/{$memberId}/honorary/create")->withError('سبب منح العضوية الشرفية مطلوب');
        }

        $durationData = RuleEngine::get('HONORARY_DURATION_YEARS');
        $years = $durationData['years'] ?? 1;
        $startDate = $data['start_date'] ?? date('Y-m-d');
        $endDate = date('Y-m-d', strtotime($startDate . " +{$years} years"));

        $renewableData = RuleEngine::get('HONORARY_RENEWABLE');
        $renewable = $renewableData['renewable'] ?? true;

        $honorary = HonoraryMember::create([
            'member_id'             => (int) $memberId,
            'granted_by_decision'   => trim($data['granted_by_decision'] ?? ''),
            'reason'                => $reason,
            'start_date'            => $startDate,
            'end_date'              => $endDate,
            'is_renewable'          => $renewable ? 1 : 0,
            'status'                => 'active',
            'notes'                 => $data['notes'] ?? null,
        ]);

        // membership_type already set at creation — activate honorary directly (no payment needed)
        if ($member['status'] !== 'active') {
            $db->update('members', [
                'status'       => 'active',
                'activated_at' => date('Y-m-d H:i:s'),
                'updated_at'   => date('Y-m-d H:i:s'),
            ], '`id` = ?', [(int) $memberId]);
            if (!$member['membership_number']) {
                \App\Modules\Members\Services\MemberNumberGenerator::assign((int) $memberId);
            }
        }

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

        return $this->redirect("/members/{$memberId}")->withSuccess("تم منح العضوية الشرفية — من {$startDate} إلى {$endDate}");
    }
}