<?php
declare(strict_types=1);

namespace App\Modules\Children\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Core\EventBus;
use App\Modules\Children\Models\Child;
use App\Modules\Children\Services\ChildFeeCalculator;
use App\Modules\Members\Services\NationalIdParser;

class ChildController extends Controller
{
    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('العضو غير موجود');
        }

        $countries = $db->select("SELECT id, nationality_ar FROM countries WHERE is_active = 1 ORDER BY nationality_ar");

        return $this->view('Children.Views.create', [
            'member'     => $member,
            'childOrder' => Child::getNextOrder((int) $memberId),
            'countries'  => $countries,
        ]);
    }

    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(trim($data['full_name_ar'] ?? ''))) $errors[] = 'اسم الابن/الابنة مطلوب';
        if (empty($data['date_of_birth'] ?? '')) $errors[] = 'تاريخ الميلاد مطلوب';
        if (empty($data['gender'] ?? '')) $errors[] = 'النوع مطلوب';
        if (empty($data['relationship'] ?? '')) $errors[] = 'نوع القرابة مطلوب';

        // Parse NID if provided
        $nid = trim($data['national_id'] ?? '');
        if ($nid !== '') {
            $parsed = NationalIdParser::parse($nid);
            if (!$parsed['is_valid']) {
                $errors = array_merge($errors, $parsed['errors']);
            } else {
                $data['date_of_birth'] = $parsed['dob'];
                $data['age_years'] = $parsed['age_years'];
                $data['age_months'] = $parsed['age_months'];
                $data['gender'] = $parsed['gender'];
            }

            // Cannot be the member themselves
            if ($nid === ($member['national_id'] ?? '')) {
                $errors[] = 'لا يمكن إضافة العضو نفسه كابن';
            }

            $dup = Child::nidExistsElsewhere($nid);
            if ($dup) {
                $errors[] = 'الرقم القومي مسجل بالفعل: ' . ($dup['data']['full_name_ar'] ?? '');
            }
        }

        // Calculate age
        if (!empty($data['date_of_birth']) && empty($data['age_years'])) {
            $age = age_from_dob($data['date_of_birth']);
            $data['age_years'] = $age['years'];
            $data['age_months'] = $age['months'];
        }

        $childAge = (int) ($data['age_years'] ?? 0);

        // Children 16+ require NID
        if ($childAge >= 16 && $nid === '') {
            $errors[] = 'الأبناء فوق 16 سنة يجب أن يكون لديهم رقم قومي';
        }

        // Age gap validation
        if (!empty($data['date_of_birth']) && !empty($member['date_of_birth'])) {
            $memberAge = age_from_dob($member['date_of_birth']);
            $ageGap = $memberAge['years'] - $childAge;
            if ($ageGap < 15) {
                $errors[] = 'الحد الأدنى لفرق السن بين العضو والابن 15 سنة';
            }
            if ($ageGap > 60) {
                $errors[] = 'الحد الأقصى لفرق السن بين العضو والابن 60 سنة';
            }
        }

        // Stepchild age check
        if (($data['relationship'] ?? '') === 'stepchild' && $childAge >= 25) {
            $errors[] = 'أبناء الزوج/الزوجة لا يمكن أن يتجاوز عمرهم 25 سنة';
        }

        // Check age 25+ not accepted
        if ($childAge >= 25 && ($data['relationship'] ?? '') !== 'stepchild') {
            $errors[] = 'لا يمكن إضافة أبناء فوق 25 سنة';
        }

        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}/children/create");
        }

        // Calculate fee
        $feeCalc = ChildFeeCalculator::calculate((int) $memberId, $data);

        if (($feeCalc['classification'] ?? '') === 'not_accepted') {
            return $this->redirect("/members/{$memberId}/children/create")
                ->withError($feeCalc['error'] ?? 'لا يمكن إضافة هذا الابن');
        }

        $childOrder = $feeCalc['child_order'] ?? Child::getNextOrder((int) $memberId);
        $classification = $feeCalc['classification'] ?? 'included';

        $child = Child::create([
            'member_id'                => (int) $memberId,
            'child_order'              => $childOrder,
            'full_name_ar'             => trim($data['full_name_ar']),
            'full_name_en'             => trim($data['full_name_en'] ?? ''),
            'national_id'              => $nid ?: null,
            'birth_certificate_number' => $data['birth_certificate_number'] ?? null,
            'date_of_birth'            => $data['date_of_birth'],
            'age_years'                => (int) ($data['age_years'] ?? 0),
            'age_months'               => (int) ($data['age_months'] ?? 0),
            'gender'                   => $data['gender'],
            'relationship'             => $data['relationship'],
            'school_faculty'           => $data['school_faculty'] ?? null,
            'nationality'              => $data['nationality'] ?? 'مصري',
            'classification'           => $classification,
            'addition_fee'             => $feeCalc['fee'] ?? '0.00',
            'status'                   => 'active',
            'remarks'                  => $data['remarks'] ?? null,
        ]);

        EventBus::dispatch('child.added', [
            'member_id'      => (int) $memberId,
            'child_id'       => (int) $child->id,
            'classification' => $classification,
            'fee'            => $feeCalc['fee'] ?? '0.00',
        ]);

        return $this->redirect("/members/{$memberId}")
            ->withSuccess('تم إضافة الابن/الابنة — التصنيف: ' . ($child->getClassificationLabel()) . ' — الرسوم: ' . money($feeCalc['fee'] ?? '0.00'));
    }

    public function show(Request $request, string $memberId, string $id): Response
    {
        $child = Child::find((int) $id);
        if (!$child || (int) $child->member_id !== (int) $memberId) {
            return $this->redirect("/members/{$memberId}")->withError('بيانات الابن غير موجودة');
        }

        $db = App::getInstance()->db();
        $member = $db->selectOne("SELECT * FROM members WHERE id = ?", [(int) $memberId]);

        return $this->view('Children.Views.show', ['member' => $member, 'child' => $child]);
    }

    public function edit(Request $request, string $memberId, string $id): Response
    {
        $child = Child::find((int) $id);
        if (!$child || (int) $child->member_id !== (int) $memberId) {
            return $this->redirect("/members/{$memberId}")->withError('بيانات الابن غير موجودة');
        }

        $db = App::getInstance()->db();
        $member = $db->selectOne("SELECT * FROM members WHERE id = ?", [(int) $memberId]);

        return $this->view('Children.Views.edit', ['member' => $member, 'child' => $child]);
    }

    public function update(Request $request, string $memberId, string $id): Response
    {
        $child = Child::find((int) $id);
        if (!$child || (int) $child->member_id !== (int) $memberId) {
            return $this->redirect("/members/{$memberId}")->withError('بيانات الابن غير موجودة');
        }

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

        $updateData = [];
        foreach (['full_name_en', 'school_faculty', 'remarks'] as $field) {
            if (array_key_exists($field, $data)) {
                $val = $data[$field];
                $updateData[$field] = ($val === '' || $val === null) ? null : $val;
            }
        }

        if (!empty($updateData)) {
            $child->update($updateData);
        }

        return $this->redirect("/members/{$memberId}")->withSuccess('تم تحديث بيانات الابن/الابنة');
    }

    public function archive(Request $request, string $memberId, string $id): Response
    {
        $child = Child::find((int) $id);
        if (!$child || (int) $child->member_id !== (int) $memberId) {
            return $this->redirect("/members/{$memberId}")->withError('بيانات الابن غير موجودة');
        }

        $reason = trim((string) $request->post('reason', ''));
        if ($reason === '') {
            return $this->redirect("/members/{$memberId}")->withError('يجب إدخال سبب الإزالة');
        }

        $employee = App::getInstance()->currentEmployee();
        $db = App::getInstance()->db();

        $db->update('children', [
            'is_archived' => 1,
            'archived_at' => date('Y-m-d H:i:s'),
            'archived_by' => $employee ? (int) $employee->id : null,
            'status'      => 'inactive',
            'updated_at'  => date('Y-m-d H:i:s'),
        ], '`id` = ?', [(int) $id]);

        EventBus::dispatch('child.removed', [
            'member_id' => (int) $memberId,
            'child_id'  => (int) $id,
            'reason'    => $reason,
        ]);

        return $this->redirect("/members/{$memberId}")->withSuccess('تم إزالة الابن/الابنة');
    }

    public function freeze(Request $request, string $memberId, string $id): Response
    {
        $child = Child::find((int) $id);
        if (!$child || (int) $child->member_id !== (int) $memberId) {
            return $this->redirect("/members/{$memberId}")->withError('بيانات الابن غير موجودة');
        }

        $reason = trim((string) $request->post('freeze_reason', 'بلوغ سن 25'));
        $db = App::getInstance()->db();

        $db->update('children', [
            'is_frozen'      => 1,
            'frozen_at'      => date('Y-m-d H:i:s'),
            'frozen_reason'  => $reason,
            'classification' => 'frozen',
            'status'         => 'frozen',
            'updated_at'     => date('Y-m-d H:i:s'),
        ], '`id` = ?', [(int) $id]);

        EventBus::dispatch('child.frozen', [
            'member_id' => (int) $memberId,
            'child_id'  => (int) $id,
            'reason'    => $reason,
        ]);

        return $this->redirect("/members/{$memberId}")->withSuccess('تم تجميد عضوية الابن/الابنة');
    }

    public function calculateFee(Request $request): Response
    {
        $memberId = (int) $request->post('member_id', 0);
        if ($memberId <= 0) {
            return $this->json(['error' => 'بيانات غير صالحة'], 422);
        }

        $result = ChildFeeCalculator::calculate($memberId, $request->all());
        return $this->json($result);
    }
}