<?php
declare(strict_types=1);

namespace App\Modules\Members\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Members\Services\NationalIdParser;
use App\Modules\Members\Services\MemberSearchService;

class MemberApiController extends Controller
{
    public function parseNid(Request $request): Response
    {
        $nid = trim((string) $request->post('national_id', ''));

        if ($nid === '') {
            return $this->json(['error' => 'الرقم القومي مطلوب', 'parsed' => ['is_valid' => false, 'errors' => ['الرقم القومي مطلوب']]]);
        }

        $parsed = NationalIdParser::parse($nid);

        // Check for duplicates across all tables
        $duplicate = null;
        if ($parsed['is_valid']) {
            $db = App::getInstance()->db();

            // Check members
            try {
                $dup = $db->selectOne(
                    "SELECT id, full_name_ar, membership_number FROM members WHERE national_id = ? AND is_archived = 0",
                    [$nid]
                );
                if ($dup) {
                    $duplicate = [
                        'type'              => 'member',
                        'id'                => (int) $dup['id'],
                        'full_name_ar'      => $dup['full_name_ar'],
                        'membership_number' => $dup['membership_number'] ?? '',
                    ];
                }
            } catch (\Throwable $e) {}

            // Check spouses
            if (!$duplicate) {
                try {
                    $dup = $db->selectOne(
                        "SELECT s.id, s.full_name_ar, s.member_id, m.membership_number 
                         FROM spouses s JOIN members m ON m.id = s.member_id 
                         WHERE s.national_id = ? AND s.is_archived = 0",
                        [$nid]
                    );
                    if ($dup) {
                        $duplicate = [
                            'type'              => 'spouse',
                            'id'                => (int) $dup['id'],
                            'full_name_ar'      => $dup['full_name_ar'],
                            'membership_number' => $dup['membership_number'] ?? '',
                            'member_id'         => (int) $dup['member_id'],
                        ];
                    }
                } catch (\Throwable $e) {}
            }

            // Check children
            if (!$duplicate) {
                try {
                    $dup = $db->selectOne(
                        "SELECT c.id, c.full_name_ar, c.member_id, m.membership_number 
                         FROM children c JOIN members m ON m.id = c.member_id 
                         WHERE c.national_id = ? AND c.is_archived = 0",
                        [$nid]
                    );
                    if ($dup) {
                        $duplicate = [
                            'type'              => 'child',
                            'id'                => (int) $dup['id'],
                            'full_name_ar'      => $dup['full_name_ar'],
                            'membership_number' => $dup['membership_number'] ?? '',
                            'member_id'         => (int) $dup['member_id'],
                        ];
                    }
                } catch (\Throwable $e) {}
            }
        }

        return $this->json([
            'parsed'    => $parsed,
            'duplicate' => $duplicate,
        ]);
    }

    public function search(Request $request): Response
    {
        $query = trim((string) $request->post('q', ''));

        if ($query === '' || mb_strlen($query) < 2) {
            return $this->json(['results' => []]);
        }

        $results = MemberSearchService::search($query, 20);

        return $this->json(['results' => $results]);
    }
}