<?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 searchGet(Request $request): Response
    {
        $query = trim((string) $request->get('q', ''));
        $exclude = (int) $request->get('exclude', 0);
        $limit = min(20, max(1, (int) $request->get('limit', 10)));

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

        $db = App::getInstance()->db();
        $like = '%' . $query . '%';
        $params = [$like, $like, $like];
        $excludeWhere = '';
        if ($exclude > 0) {
            $excludeWhere = ' AND id != ?';
            $params[] = $exclude;
        }
        $params[] = $limit;

        $rows = $db->select(
            "SELECT id, full_name_ar, national_id, phone_mobile, membership_number, status
             FROM members WHERE is_archived = 0 AND (full_name_ar LIKE ? OR national_id LIKE ? OR membership_number LIKE ?){$excludeWhere}
             ORDER BY full_name_ar ASC LIMIT ?",
            $params
        );

        return $this->json($rows);
    }

    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]);
    }
}