<?php
declare(strict_types=1);

namespace App\Modules\Members\Controllers;

use App\Core\App;
use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Modules\Members\Services\RetroactiveMembershipService;

class RetroactiveWizardController extends Controller
{
    private static function isSuperAdmin(): bool
    {
        $employee = App::getInstance()->currentEmployee();
        if (!$employee) return false;
        $db = App::getInstance()->db();
        $row = $db->selectOne(
            "SELECT 1 FROM employee_roles er JOIN roles r ON r.id = er.role_id WHERE er.employee_id = ? AND r.role_code = 'super_admin' AND er.is_active = 1 LIMIT 1",
            [(int) $employee->id]
        );
        return $row !== null;
    }

    public function index(Request $request): Response
    {
        if (!self::isSuperAdmin()) {
            throw new \RuntimeException('هذه الأداة متاحة فقط لمدير النظام', 403);
        }

        $db = App::getInstance()->db();
        $branches = $db->select("SELECT id, name_ar FROM branches WHERE is_active = 1 ORDER BY name_ar");
        $qualifications = $db->select("SELECT id, name_ar FROM qualifications WHERE is_active = 1 ORDER BY sort_order");

        return $this->view('Members.Views.retroactive-wizard', [
            'branches'       => $branches,
            'qualifications' => $qualifications,
        ]);
    }

    public function store(Request $request): Response
    {
        if (!self::isSuperAdmin()) {
            throw new \RuntimeException('هذه الأداة متاحة فقط لمدير النظام', 403);
        }

        $data = $this->collectWizardData($request);
        $result = RetroactiveMembershipService::createRetroactiveMember($data);

        if (!$result['success']) {
            return $this->redirect('/members/retroactive-wizard')
                ->withError('فشل إنشاء العضوية: ' . ($result['error'] ?? 'خطأ غير معروف'));
        }

        $memberId = $result['data']['member_id'];
        return $this->redirect('/members/' . $memberId)
            ->withSuccess('تم إنشاء العضوية بأثر رجعي بنجاح — رقم العضوية: ' . $result['data']['membership_number']);
    }

    public function preview(Request $request): Response
    {
        if (!self::isSuperAdmin()) {
            return $this->json(['error' => 'غير مصرح'], 403);
        }

        $data = $this->collectWizardData($request);

        $preview = [
            'member_name'     => $data['full_name_ar'] ?? '',
            'join_date'       => $data['join_date'] ?? '',
            'membership_type' => $data['membership_type'] ?? 'working',
            'membership_value'=> $data['membership_value'] ?? '0.00',
            'payment_method'  => $data['membership_payment_method'] ?? 'cash',
            'form_fee'        => $data['form_fee_amount'] ?? '0.00',
            'spouses_count'   => count($data['spouses'] ?? []),
            'children_count'  => count($data['children'] ?? []),
            'temp_members_count' => count($data['temporary_members'] ?? []),
            'subscriptions'   => $data['subscriptions'] ?? [],
            'violations'      => $data['violations'] ?? [],
            'has_installment' => ($data['membership_payment_method'] ?? 'cash') === 'installment',
            'installment_plan'=> $data['installment_plan'] ?? null,
        ];

        return $this->json(['success' => true, 'preview' => $preview]);
    }

    private function collectWizardData(Request $request): array
    {
        $post = $_POST;

        $data = [
            // Step 1: Basic member info
            'full_name_ar'        => trim($post['full_name_ar'] ?? ''),
            'full_name_en'        => trim($post['full_name_en'] ?? '') ?: null,
            'membership_number'   => trim($post['membership_number'] ?? '') ?: null,
            'national_id'         => trim($post['national_id'] ?? '') ?: null,
            'passport_number'     => trim($post['passport_number'] ?? '') ?: null,
            'date_of_birth'       => $post['date_of_birth'] ?? null,
            'gender'              => $post['gender'] ?? 'male',
            'phone_mobile'        => trim($post['phone_mobile'] ?? '') ?: null,
            'phone_home'          => trim($post['phone_home'] ?? '') ?: null,
            'email'               => trim($post['email'] ?? '') ?: null,
            'branch_id'           => (int) ($post['branch_id'] ?? 1),
            'membership_type'     => $post['membership_type'] ?? 'working',
            'member_category'     => $post['member_category'] ?? 'working_member',
            'nationality'         => $post['nationality'] ?? 'egyptian',
            'qualification_id'    => !empty($post['qualification_id']) ? (int) $post['qualification_id'] : null,
            'occupation'          => trim($post['occupation'] ?? '') ?: null,
            'residence_address'   => trim($post['residence_address'] ?? '') ?: null,
            'area'                => trim($post['area'] ?? '') ?: null,
            'governorate'         => trim($post['governorate'] ?? '') ?: null,

            // Step 2: Dates & activation
            'join_date'           => $post['join_date'] ?? date('Y-m-d'),
            'form_date'           => $post['form_date'] ?? ($post['join_date'] ?? date('Y-m-d')),

            // Step 3: Financial - form fee
            'form_fee_amount'     => $post['form_fee_amount'] ?? '505.00',
            'form_fee_method'     => $post['form_fee_method'] ?? 'cash',
            'form_fee_check_number' => $post['form_fee_check_number'] ?? null,
            'form_fee_check_bank'   => $post['form_fee_check_bank'] ?? null,
            'form_fee_check_date'   => $post['form_fee_check_date'] ?? null,

            // Step 3: Financial - membership value
            'membership_value'           => $post['membership_value'] ?? '150000.00',
            'membership_payment_method'  => $post['membership_payment_method'] ?? 'cash',
            'membership_payment_date'    => $post['membership_payment_date'] ?? ($post['join_date'] ?? date('Y-m-d')),
            'membership_check_number'    => $post['membership_check_number'] ?? null,
            'membership_check_bank'      => $post['membership_check_bank'] ?? null,
            'membership_check_date'      => $post['membership_check_date'] ?? null,
            'membership_visa_reference'  => $post['membership_visa_reference'] ?? null,
            'membership_transfer_reference' => $post['membership_transfer_reference'] ?? null,
            'membership_transfer_bank'   => $post['membership_transfer_bank'] ?? null,
            'discount_amount'            => $post['discount_amount'] ?? '0.00',
            'payment_method'             => $post['membership_payment_method'] ?? 'cash',
        ];

        // Step 4: Installment plan
        if (($post['membership_payment_method'] ?? 'cash') === 'installment') {
            $paidInstallments = [];
            if (!empty($post['inst_paid_numbers'])) {
                $numbers = explode(',', $post['inst_paid_numbers']);
                foreach ($numbers as $num) {
                    $num = (int) trim($num);
                    if ($num > 0) {
                        $paidInstallments[] = [
                            'number'         => $num,
                            'paid_date'      => $post["inst_paid_date_{$num}"] ?? null,
                            'payment_method' => $post["inst_paid_method_{$num}"] ?? 'cash',
                            'check_number'   => $post["inst_paid_check_{$num}"] ?? null,
                            'check_bank'     => $post["inst_paid_bank_{$num}"] ?? null,
                            'check_date'     => $post["inst_paid_checkdate_{$num}"] ?? null,
                        ];
                    }
                }
            }

            $cheques = [];
            $chequeCount = (int) ($post['cheque_count'] ?? 0);
            for ($i = 1; $i <= $chequeCount; $i++) {
                if (!empty($post["cheque_number_{$i}"])) {
                    $cheques[] = [
                        'cheque_number' => $post["cheque_number_{$i}"],
                        'bank_name'     => $post["cheque_bank_{$i}"] ?? '',
                        'cheque_date'   => $post["cheque_date_{$i}"] ?? '',
                        'cheque_amount' => $post["cheque_amount_{$i}"] ?? '0.00',
                    ];
                }
            }

            $data['installment_plan'] = [
                'total_amount'         => $post['membership_value'] ?? '150000.00',
                'down_payment'         => $post['inst_down_payment'] ?? '37500.00',
                'months'               => (int) ($post['inst_months'] ?? 12),
                'start_date'           => $post['inst_start_date'] ?? ($post['join_date'] ?? date('Y-m-d')),
                'interest_rate'        => $post['inst_interest_rate'] ?? '22.00',
                'down_payment_method'  => $post['inst_down_method'] ?? 'cash',
                'down_check_number'    => $post['inst_down_check_number'] ?? null,
                'down_check_bank'      => $post['inst_down_check_bank'] ?? null,
                'down_check_date'      => $post['inst_down_check_date'] ?? null,
                'paid_installments'    => $paidInstallments,
                'cheques'              => $cheques,
            ];
        }

        // Step 5: Dependents
        $data['spouses'] = [];
        $spouseCount = (int) ($post['spouse_count'] ?? 0);
        for ($i = 1; $i <= $spouseCount; $i++) {
            if (!empty($post["spouse_name_{$i}"])) {
                $data['spouses'][] = [
                    'full_name_ar'    => $post["spouse_name_{$i}"],
                    'national_id'     => $post["spouse_nid_{$i}"] ?? null,
                    'date_of_birth'   => $post["spouse_dob_{$i}"] ?? null,
                    'nationality'     => $post["spouse_nationality_{$i}"] ?? 'مصري',
                    'marriage_date'   => $post["spouse_marriage_date_{$i}"] ?? null,
                    'phone_mobile'    => $post["spouse_phone_{$i}"] ?? null,
                    'join_date'       => $post["spouse_join_date_{$i}"] ?? ($post['join_date'] ?? date('Y-m-d')),
                    'addition_fee'    => $post["spouse_fee_{$i}"] ?? '0.00',
                    'has_separate_fee'=> !empty($post["spouse_separate_fee_{$i}"]),
                    'payment_method'  => $post["spouse_pay_method_{$i}"] ?? 'cash',
                    'payment_date'    => $post["spouse_pay_date_{$i}"] ?? null,
                ];
            }
        }

        $data['children'] = [];
        $childCount = (int) ($post['child_count'] ?? 0);
        for ($i = 1; $i <= $childCount; $i++) {
            if (!empty($post["child_name_{$i}"])) {
                $data['children'][] = [
                    'full_name_ar'    => $post["child_name_{$i}"],
                    'national_id'     => $post["child_nid_{$i}"] ?? null,
                    'date_of_birth'   => $post["child_dob_{$i}"] ?? null,
                    'gender'          => $post["child_gender_{$i}"] ?? 'male',
                    'join_date'       => $post["child_join_date_{$i}"] ?? ($post['join_date'] ?? date('Y-m-d')),
                    'addition_fee'    => $post["child_fee_{$i}"] ?? '0.00',
                    'has_separate_fee'=> !empty($post["child_separate_fee_{$i}"]),
                    'payment_method'  => $post["child_pay_method_{$i}"] ?? 'cash',
                    'payment_date'    => $post["child_pay_date_{$i}"] ?? null,
                ];
            }
        }

        $data['temporary_members'] = [];
        $tempCount = (int) ($post['temp_member_count'] ?? 0);
        for ($i = 1; $i <= $tempCount; $i++) {
            if (!empty($post["temp_name_{$i}"])) {
                $data['temporary_members'][] = [
                    'full_name_ar'           => $post["temp_name_{$i}"],
                    'national_id'            => $post["temp_nid_{$i}"] ?? null,
                    'date_of_birth'          => $post["temp_dob_{$i}"] ?? null,
                    'gender'                 => $post["temp_gender_{$i}"] ?? 'male',
                    'category'               => $post["temp_category_{$i}"] ?? 'parent',
                    'relationship_to_member' => $post["temp_relationship_{$i}"] ?? null,
                    'join_date'              => $post["temp_join_date_{$i}"] ?? ($post['join_date'] ?? date('Y-m-d')),
                    'addition_fee'           => $post["temp_fee_{$i}"] ?? '0.00',
                    'has_separate_fee'       => !empty($post["temp_separate_fee_{$i}"]),
                    'payment_method'         => $post["temp_pay_method_{$i}"] ?? 'cash',
                    'payment_date'           => $post["temp_pay_date_{$i}"] ?? null,
                ];
            }
        }

        // Step 6: Subscriptions
        $data['subscriptions'] = [];
        $subCount = (int) ($post['subscription_count'] ?? 0);
        for ($i = 1; $i <= $subCount; $i++) {
            if (!empty($post["sub_year_{$i}"])) {
                $data['subscriptions'][] = [
                    'financial_year'  => $post["sub_year_{$i}"],
                    'person_type'     => $post["sub_person_type_{$i}"] ?? 'member',
                    'person_index'    => (int) ($post["sub_person_index_{$i}"] ?? 0),
                    'person_name'     => $post["sub_person_name_{$i}"] ?? $data['full_name_ar'],
                    'base_amount'     => $post["sub_base_{$i}"] ?? '492.00',
                    'development_fee' => $post["sub_dev_fee_{$i}"] ?? '35.00',
                    'total_amount'    => $post["sub_total_{$i}"] ?? '527.00',
                    'paid_amount'     => $post["sub_paid_{$i}"] ?? '0.00',
                    'fine_amount'     => $post["sub_fine_{$i}"] ?? '0.00',
                    'status'          => $post["sub_status_{$i}"] ?? 'pending',
                    'paid_date'       => $post["sub_paid_date_{$i}"] ?? null,
                    'payment_method'  => $post["sub_pay_method_{$i}"] ?? 'cash',
                    'discount_amount' => $post["sub_discount_{$i}"] ?? '0.00',
                ];
            }
        }

        // Step 7: Violations & Fines
        $data['violations'] = [];
        $violationCount = (int) ($post['violation_count'] ?? 0);
        for ($i = 1; $i <= $violationCount; $i++) {
            if (!empty($post["violation_desc_{$i}"])) {
                $data['violations'][] = [
                    'violation_date'      => $post["violation_date_{$i}"] ?? date('Y-m-d'),
                    'description'         => $post["violation_desc_{$i}"],
                    'evidence_notes'      => $post["violation_evidence_{$i}"] ?? null,
                    'fine_amount'         => $post["violation_fine_amount_{$i}"] ?? '0.00',
                    'penalty_type'        => $post["violation_penalty_type_{$i}"] ?? 'fine',
                    'fine_status'         => $post["violation_fine_status_{$i}"] ?? 'imposed',
                    'fine_payment_method' => $post["violation_fine_method_{$i}"] ?? 'cash',
                    'fine_paid_date'      => $post["violation_fine_paid_date_{$i}"] ?? null,
                    'suspension_from'     => $post["violation_suspension_from_{$i}"] ?? null,
                    'suspension_to'       => $post["violation_suspension_to_{$i}"] ?? null,
                ];
            }
        }

        return $data;
    }
}
