<?php
require_once 'auth.php';
restore_login_from_cookie();

if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'officer') {
    header("Location: index.php");
    exit();
}

if (!function_exists('e')) {
    function e($value) {
        return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
    }
}

$area_options = [
    'আড়াইহাজার ইউনিয়ন',
    'সাতগ্রাম ইউনিয়ন',
    'দুপ্তারা ইউনিয়ন',
    'ব্রাক্ষন্দী ইউনিয়ন',
    'ফতেপুর ইউনিয়ন',
    'বিশনন্দী ইউনিয়ন',
    'মাহমুদপুর ইউনিয়ন',
    'হাইজাদী ইউনিয়ন',
    'উচিৎপুরা ইউনিয়ন',
    'কালাপাহাড়িয়া ইউনিয়ন',
    'চরদিঘলদী ইউনিয়ন',
    'বাহেরচর ইউনিয়ন',
    'খাগকান্দা ইউনিয়ন',
    'আড়াইহাজার পৌরসভা',
    'গোপালদী পৌরসভা'
];

define('CARD_PREFIX', 'AGH ');
define('CARD_START_NUMBER', 2501);

function card_number_to_int($card_number) {
    preg_match('/(\d+)/', (string) $card_number, $match);
    return isset($match[1]) ? (int) $match[1] : 0;
}

function get_next_card_number($conn) {
    $next_number = CARD_START_NUMBER;
    $result = $conn->query("SELECT card_number FROM agh_patients ORDER BY id DESC LIMIT 1");

    if ($result && $row = $result->fetch_assoc()) {
        $last_number = card_number_to_int($row['card_number']);
        if ($last_number > 0) {
            $next_number = $last_number + 1;
        }
    }

    return CARD_PREFIX . $next_number;
}

function generate_locked_card_number($conn) {
    $lock_result = $conn->query("SELECT GET_LOCK('agh_card_number_lock', 10) AS locked");
    $lock_row = $lock_result ? $lock_result->fetch_assoc() : null;

    if (!$lock_row || (int) $lock_row['locked'] !== 1) {
        throw new Exception("কার্ড নম্বর তৈরি করা যায়নি। আবার চেষ্টা করুন।");
    }

    $next_card_number = get_next_card_number($conn);

    while (true) {
        $stmt = $conn->prepare("SELECT id FROM agh_patients WHERE card_number = ? LIMIT 1");
        $stmt->bind_param("s", $next_card_number);
        $stmt->execute();
        $duplicate = $stmt->get_result();
        $stmt->close();

        if (!$duplicate || $duplicate->num_rows === 0) {
            break;
        }

        $next_number = card_number_to_int($next_card_number) + 1;
        $next_card_number = CARD_PREFIX . $next_number;
    }

    return $next_card_number;
}

function release_card_number_lock($conn) {
    $conn->query("SELECT RELEASE_LOCK('agh_card_number_lock')");
}

$officer_id = (int) $_SESSION['user_id'];
$success_msg = "";
$error_msg = "";
$preview_card_number = get_next_card_number($conn);

$old = [
    'mobile' => '',
    'area_name' => '',
    'village_name' => '',
    'members' => [
        ['name' => '', 'age' => '', 'problem' => '']
    ]
];

if (isset($_POST['save_patient'])) {
    $mobile = trim($_POST['mobile'] ?? '');
    $area_name = trim($_POST['area_name'] ?? '');
    $village_name = trim($_POST['village_name'] ?? '');

    $names = $_POST['member_name'] ?? [];
    $ages = $_POST['age'] ?? [];
    $problems = $_POST['initial_problem'] ?? [];

    $old['mobile'] = $mobile;
    $old['area_name'] = $area_name;
    $old['village_name'] = $village_name;
    $old['members'] = [];

    $transaction_started = false;
    $lock_taken = false;

    try {
        if ($mobile === '') {
            throw new Exception("মোবাইল নম্বর অবশ্যই দিতে হবে।");
        }

        if (!in_array($area_name, $area_options, true)) {
            throw new Exception("সঠিক ইউনিয়ন বা পৌরসভা নির্বাচন করুন।");
        }

        if ($village_name === '') {
            throw new Exception("গ্রামের নাম লিখুন।");
        }

        if (!preg_match('/^[\x{0980}-\x{09FF}\s]+$/u', $village_name)) {
            throw new Exception("গ্রামের নাম শুধু বাংলায় লিখুন।");
        }

        $members = [];

        for ($i = 0; $i < count($names); $i++) {
            $problem = trim($problems[$i] ?? '');
            if ($problem === '') {
                $problem = 'নাই।';
            }

            $member = [
                'name' => trim($names[$i] ?? ''),
                'age' => trim($ages[$i] ?? ''),
                'problem' => $problem
            ];

            $old['members'][] = $member;

            if ($member['name'] !== '') {
                if (!preg_match('/^[\x{0980}-\x{09FF}\s]+$/u', $member['name'])) {
                    throw new Exception("সদস্যের নাম শুধু বাংলায় লিখুন।");
                }

                if ($member['age'] === '') {
                    throw new Exception("প্রতিটি সদস্যের বয়স দিন।");
                }

                $members[] = $member;
            }
        }

        if (count($members) === 0) {
            throw new Exception("কমপক্ষে একজন পরিবারের সদস্যের তথ্য দিন।");
        }

        $address = $area_name . ' | গ্রাম: ' . $village_name;

        $card_number = generate_locked_card_number($conn);
        $lock_taken = true;

        $conn->begin_transaction();
        $transaction_started = true;

        $stmt = $conn->prepare("
            INSERT INTO agh_patients (card_number, mobile, address, marketing_officer_id)
            VALUES (?, ?, ?, ?)
        ");
        $stmt->bind_param("sssi", $card_number, $mobile, $address, $officer_id);
        $stmt->execute();

        $patient_id = $conn->insert_id;
        $stmt->close();

        $stmt = $conn->prepare("
            INSERT INTO agh_family_members (patient_id, member_name, age, initial_problem)
            VALUES (?, ?, ?, ?)
        ");

        foreach ($members as $member) {
            $member_name = $member['name'];
            $age = $member['age'];
            $problem = $member['problem'];

            $stmt->bind_param("isss", $patient_id, $member_name, $age, $problem);
            $stmt->execute();
        }

        $stmt->close();
        $conn->commit();
        release_card_number_lock($conn);
        $lock_taken = false;

        if (function_exists('sendSMS')) {
            $sms_message = "স্বাগতম! আড়াইহাজার জেনারেল হাসপাতালে (AGH) আপনার হেলথ কার্ড (নং: {$card_number}) সফলভাবে তৈরি হয়েছে।";
            sendSMS($mobile, $sms_message);
        }

        $success_msg = "নতুন হেলথ কার্ড {$card_number} সফলভাবে তৈরি হয়েছে।";

        $old = [
            'mobile' => '',
            'area_name' => '',
            'village_name' => '',
            'members' => [
                ['name' => '', 'age' => '', 'problem' => '']
            ]
        ];

        $preview_card_number = get_next_card_number($conn);
    } catch (Exception $e) {
        if ($transaction_started) {
            $conn->rollback();
        }

        if ($lock_taken) {
            release_card_number_lock($conn);
        }

        $error_msg = "দুঃখিত, তথ্য সেভ করা যায়নি। " . $e->getMessage();

        if (empty($old['members'])) {
            $old['members'] = [
                ['name' => '', 'age' => '', 'problem' => '']
            ];
        }

        $preview_card_number = get_next_card_number($conn);
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add New Patient - AGH</title>
    <link rel="icon" type="image/png" href="favicon.png">

    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Bengali:wght@300;400;500;600;700;800&family=Poppins:wght@400;500;600;700;800&display=swap" rel="stylesheet">

    <style>
        body { font-family: 'Noto Sans Bengali', 'Poppins', sans-serif; }

        .page-bg {
            background:
                radial-gradient(circle at top left, rgba(14, 165, 233, 0.18), transparent 34%),
                radial-gradient(circle at bottom right, rgba(16, 185, 129, 0.18), transparent 34%),
                linear-gradient(135deg, #f8fafc 0%, #eff6ff 48%, #ecfdf5 100%);
        }

        .glass {
            background: rgba(255, 255, 255, 0.78);
            backdrop-filter: blur(18px);
            -webkit-backdrop-filter: blur(18px);
        }

        .panel {
            border: 1px solid rgba(226, 232, 240, 0.9);
            background: rgba(255, 255, 255, 0.9);
            box-shadow: 0 24px 70px rgba(15, 23, 42, 0.08);
        }

        .field {
            width: 100%;
            border-radius: 1rem;
            border: 1px solid #e2e8f0;
            background: rgba(248, 250, 252, 0.92);
            padding: 0.95rem 1rem;
            color: #0f172a;
            outline: none;
            transition: 0.2s ease;
        }

        .field:focus {
            border-color: #0ea5e9;
            background: #ffffff;
            box-shadow: 0 0 0 4px rgba(14, 165, 233, 0.13);
        }

        .field[readonly] {
            background: linear-gradient(135deg, #e0f2fe, #ecfdf5);
            color: #0369a1;
            font-weight: 800;
            cursor: not-allowed;
        }

        .label {
            display: block;
            margin-bottom: 0.5rem;
            font-size: 0.875rem;
            font-weight: 700;
            color: #475569;
        }

        .member-row { position: relative; }
        .member-row + .member-row { margin-top: 2rem; }

        .member-row + .member-row::before {
            content: "";
            position: absolute;
            left: 1rem;
            right: 1rem;
            top: -1rem;
            height: 1px;
            background: linear-gradient(to right, transparent, #38bdf8, #10b981, transparent);
        }

        .member-divider-badge { display: none; }
        .member-row + .member-row .member-divider-badge { display: inline-flex; }
    </style>
</head>

<body class="page-bg min-h-screen text-slate-800 pb-12">

    <nav class="sticky top-0 z-50 border-b border-white/70 glass shadow-sm">
        <div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
            <div class="flex items-center justify-between gap-4">
                <a href="officer_dashboard.php" class="inline-flex items-center gap-2 rounded-full bg-white border border-slate-100 px-4 py-2 text-sm font-bold text-sky-700 shadow-sm hover:bg-sky-50 transition">
                    <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24">
                        <path d="M19 12H5"></path>
                        <path d="m12 19-7-7 7-7"></path>
                    </svg>
                    ড্যাশবোর্ড
                </a>

                <div class="text-right">
                    <h1 class="text-lg sm:text-xl font-extrabold text-slate-900">নতুন কার্ড ইস্যু</h1>
                    <p class="text-xs text-slate-500">AGH Health Card System</p>
                </div>
            </div>
        </div>
    </nav>

    <main class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">

        <section class="relative overflow-hidden rounded-[2rem] bg-gradient-to-br from-sky-700 via-blue-700 to-emerald-600 text-white p-6 sm:p-8 lg:p-10 shadow-2xl shadow-sky-200 mb-8">
            <div class="absolute inset-0 opacity-15 bg-[linear-gradient(135deg,white_1px,transparent_1px)] bg-[length:24px_24px]"></div>

            <div class="relative z-10 flex flex-col lg:flex-row lg:items-end lg:justify-between gap-6">
                <div>
                    <p class="text-sm font-semibold uppercase tracking-[0.28em] text-sky-100">New Registration</p>
                    <h2 class="mt-4 text-3xl sm:text-5xl font-extrabold leading-tight">হেলথ কার্ড তথ্য যুক্ত করুন</h2>
                    <p class="mt-4 max-w-2xl text-sky-50 leading-8">
                        কার্ড নম্বর এখন database থেকে automatic আসবে। অফিসার এটি পরিবর্তন করতে পারবে না।
                    </p>
                </div>

                <div class="rounded-3xl bg-white/15 border border-white/20 p-5 min-w-full sm:min-w-[280px]">
                    <p class="text-sm font-bold text-sky-100">পরবর্তী কার্ড নম্বর</p>
                    <p class="mt-2 text-3xl font-extrabold"><?php echo e($preview_card_number); ?></p>
                </div>
            </div>
        </section>

        <?php if ($success_msg): ?>
            <div class="mb-6 rounded-3xl border border-emerald-200 bg-emerald-50 px-5 py-4 text-emerald-800 font-bold flex items-center gap-3">
                <span class="h-10 w-10 rounded-2xl bg-emerald-100 flex items-center justify-center">
                    <svg width="22" height="22" fill="none" stroke="currentColor" stroke-width="2.4" viewBox="0 0 24 24">
                        <path d="M20 6 9 17l-5-5"></path>
                    </svg>
                </span>
                <?php echo e($success_msg); ?>
            </div>
        <?php endif; ?>

        <?php if ($error_msg): ?>
            <div class="mb-6 rounded-3xl border border-red-200 bg-red-50 px-5 py-4 text-red-700 font-bold flex items-center gap-3">
                <span class="h-10 w-10 rounded-2xl bg-red-100 flex items-center justify-center">
                    <svg width="22" height="22" fill="none" stroke="currentColor" stroke-width="2.4" viewBox="0 0 24 24">
                        <path d="M12 9v4"></path>
                        <path d="M12 17h.01"></path>
                        <path d="M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z"></path>
                    </svg>
                </span>
                <?php echo e($error_msg); ?>
            </div>
        <?php endif; ?>

        <form action="" method="POST" class="space-y-7" onsubmit="fillEmptyProblems()">

            <section class="panel rounded-[2rem] p-5 sm:p-7">
                <div class="flex items-center gap-3 mb-6">
                    <div class="h-12 w-12 rounded-2xl bg-sky-100 text-sky-600 flex items-center justify-center">
                        <svg width="26" height="26" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                            <rect x="3" y="4" width="18" height="16" rx="2"></rect>
                            <path d="M7 8h10"></path>
                            <path d="M7 12h6"></path>
                            <path d="M7 16h4"></path>
                        </svg>
                    </div>
                    <div>
                        <h3 class="text-xl font-extrabold text-slate-900">কার্ডের মূল তথ্য</h3>
                        <p class="text-sm text-slate-500 mt-1">কার্ড নম্বর, মোবাইল, ইউনিয়ন/পৌরসভা এবং গ্রামের নাম</p>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                    <div>
                        <label for="card_number" class="label">হেলথ কার্ড নম্বর</label>
                        <input id="card_number" type="text" value="<?php echo e($preview_card_number); ?>" class="field" readonly>
                        <p class="mt-2 text-xs font-semibold text-slate-400">এই নম্বরটি system automatic তৈরি করবে</p>
                    </div>

                    <div>
                        <label for="mobile" class="label">মোবাইল নম্বর *</label>
                        <input id="mobile" type="text" name="mobile" required inputmode="tel" value="<?php echo e($old['mobile']); ?>" class="field" placeholder="01XXXXXXXXX">
                    </div>

                    <div>
                        <label for="area_name" class="label">ইউনিয়ন / পৌরসভা *</label>
                        <select id="area_name" name="area_name" required class="field cursor-pointer">
                            <option value="">নির্বাচন করুন</option>
                            <?php foreach ($area_options as $area): ?>
                                <option value="<?php echo e($area); ?>" <?php echo $old['area_name'] === $area ? 'selected' : ''; ?>>
                                    <?php echo e($area); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div>
                        <label for="village_name" class="label">গ্রামের নাম *</label>
                        <input
                            id="village_name"
                            type="text"
                            name="village_name"
                            required
                            lang="bn"
                            value="<?php echo e($old['village_name']); ?>"
                            class="field"
                            placeholder="যেমন: কামরানীর চর"
                            oninput="banglaOnly(this)">
                        <p class="mt-2 text-xs font-semibold text-slate-400">এখানে শুধু বাংলা লেখা যাবে</p>
                    </div>

                    <div class="md:col-span-2">
                        <div class="rounded-3xl border border-sky-100 bg-sky-50/80 px-5 py-4">
                            <p class="text-xs font-extrabold uppercase tracking-wider text-sky-600">Address Format</p>
                            <p id="address_preview" class="mt-2 text-sm sm:text-base font-bold text-slate-700">
                                ইউনিয়ন/পৌরসভা | গ্রাম: গ্রামের নাম
                            </p>
                        </div>
                    </div>
                </div>
            </section>

            <section class="panel rounded-[2rem] p-5 sm:p-7">
                <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
                    <div class="flex items-center gap-3">
                        <div class="h-12 w-12 rounded-2xl bg-emerald-100 text-emerald-600 flex items-center justify-center">
                            <svg width="26" height="26" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                                <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"></path>
                                <circle cx="9" cy="7" r="4"></circle>
                                <path d="M22 21v-2a4 4 0 0 0-3-3.87"></path>
                                <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
                            </svg>
                        </div>
                        <div>
                            <h3 class="text-xl font-extrabold text-slate-900">পরিবারের সদস্য</h3>
                            <p class="text-sm text-slate-500 mt-1">প্রতিটি সদস্য আলাদা কার্ড ব্লকে দেখানো হবে</p>
                        </div>
                    </div>

                    <button type="button" onclick="addMemberRow()" class="inline-flex items-center justify-center gap-2 rounded-2xl bg-sky-600 hover:bg-sky-700 text-white px-5 py-3 text-sm font-extrabold transition shadow-lg shadow-sky-100">
                        <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.4" viewBox="0 0 24 24">
                            <path d="M12 5v14"></path>
                            <path d="M5 12h14"></path>
                        </svg>
                        সদস্য যোগ করুন
                    </button>
                </div>

                <div id="member_container" class="space-y-0">
                    <?php foreach ($old['members'] as $index => $member): ?>
                        <div class="member-row rounded-3xl bg-slate-50 border border-slate-100 p-4 sm:p-5">
                            <div class="member-divider-badge absolute left-1/2 top-[-1.72rem] -translate-x-1/2 rounded-full bg-white border border-sky-100 px-3 py-1 text-[11px] font-extrabold text-sky-600 shadow-sm">
                                নতুন সদস্য
                            </div>

                            <div class="flex items-center justify-between gap-3 mb-4">
                                <div class="inline-flex items-center gap-2 rounded-full bg-white border border-slate-100 px-3 py-2 shadow-sm">
                                    <span class="member-number h-7 w-7 rounded-full bg-emerald-100 text-emerald-700 flex items-center justify-center text-sm font-extrabold">
                                        <?php echo e($index + 1); ?>
                                    </span>
                                    <span class="member-title text-sm font-extrabold text-slate-700">সদস্য <?php echo e($index + 1); ?></span>
                                </div>

                                <button type="button" onclick="removeMemberRow(this)" class="<?php echo $index === 0 ? 'hidden' : ''; ?> h-10 w-10 rounded-2xl bg-red-50 hover:bg-red-100 text-red-600 flex items-center justify-center transition" title="সদস্য বাদ দিন">
                                    <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24">
                                        <path d="M3 6h18"></path>
                                        <path d="M8 6V4h8v2"></path>
                                        <path d="M19 6l-1 14H6L5 6"></path>
                                    </svg>
                                </button>
                            </div>

                            <div class="grid grid-cols-1 lg:grid-cols-[1.4fr_0.5fr_1.4fr] gap-3">
                                <div>
                                    <label class="label">সদস্যের নাম *</label>
                                    <input type="text" name="member_name[]" required lang="bn" value="<?php echo e($member['name']); ?>" class="field" placeholder="নাম লিখুন" oninput="banglaOnly(this)">
                                    <p class="mt-2 text-xs font-semibold text-slate-400">এখানে শুধু বাংলা লেখা যাবে</p>
                                </div>

                                <div>
                                    <label class="label">বয়স *</label>
                                    <input type="number" name="age[]" required min="0" value="<?php echo e($member['age']); ?>" class="field" placeholder="বয়স">
                                </div>

                                <div>
                                    <label class="label">বর্তমান সমস্যা</label>
                                    <input type="text" name="initial_problem[]" value="<?php echo e($member['problem']); ?>" class="field problem-field" placeholder="যদি থাকে" onkeydown="handleProblemEnter(event, this)">
                                    <p class="mt-2 text-xs font-semibold text-slate-400">ফাঁকা থাকলে auto “নাই।” বসবে</p>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </section>

            <div class="flex flex-col sm:flex-row gap-4">
                <a href="officer_dashboard.php" class="sm:w-1/3 inline-flex items-center justify-center rounded-2xl bg-white border border-slate-200 px-6 py-4 font-extrabold text-slate-700 hover:bg-slate-50 transition">
                    বাতিল করুন
                </a>

                <button type="submit" name="save_patient" class="sm:w-2/3 inline-flex items-center justify-center gap-3 rounded-2xl bg-gradient-to-r from-sky-600 to-emerald-500 px-6 py-4 font-extrabold text-white shadow-xl shadow-sky-200 transition hover:-translate-y-0.5 hover:shadow-2xl">
                    সব তথ্য জমা দিন
                    <svg width="21" height="21" fill="none" stroke="currentColor" stroke-width="2.4" viewBox="0 0 24 24">
                        <path d="M20 6 9 17l-5-5"></path>
                    </svg>
                </button>
            </div>
        </form>

    </main>

    <template id="member_template">
        <div class="member-row rounded-3xl bg-slate-50 border border-slate-100 p-4 sm:p-5">
            <div class="member-divider-badge absolute left-1/2 top-[-1.72rem] -translate-x-1/2 rounded-full bg-white border border-sky-100 px-3 py-1 text-[11px] font-extrabold text-sky-600 shadow-sm">
                নতুন সদস্য
            </div>

            <div class="flex items-center justify-between gap-3 mb-4">
                <div class="inline-flex items-center gap-2 rounded-full bg-white border border-slate-100 px-3 py-2 shadow-sm">
                    <span class="member-number h-7 w-7 rounded-full bg-emerald-100 text-emerald-700 flex items-center justify-center text-sm font-extrabold">1</span>
                    <span class="member-title text-sm font-extrabold text-slate-700">সদস্য 1</span>
                </div>

                <button type="button" onclick="removeMemberRow(this)" class="h-10 w-10 rounded-2xl bg-red-50 hover:bg-red-100 text-red-600 flex items-center justify-center transition" title="সদস্য বাদ দিন">
                    <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24">
                        <path d="M3 6h18"></path>
                        <path d="M8 6V4h8v2"></path>
                        <path d="M19 6l-1 14H6L5 6"></path>
                    </svg>
                </button>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-[1.4fr_0.5fr_1.4fr] gap-3">
                <div>
                    <label class="label">সদস্যের নাম *</label>
                    <input type="text" name="member_name[]" required lang="bn" class="field" placeholder="নাম লিখুন" oninput="banglaOnly(this)">
                    <p class="mt-2 text-xs font-semibold text-slate-400">এখানে শুধু বাংলা লেখা যাবে</p>
                </div>

                <div>
                    <label class="label">বয়স *</label>
                    <input type="number" name="age[]" required min="0" class="field" placeholder="বয়স">
                </div>

                <div>
                    <label class="label">বর্তমান সমস্যা</label>
                    <input type="text" name="initial_problem[]" class="field problem-field" placeholder="যদি থাকে" onkeydown="handleProblemEnter(event, this)">
                    <p class="mt-2 text-xs font-semibold text-slate-400">ফাঁকা থাকলে auto “নাই।” বসবে</p>
                </div>
            </div>
        </div>
    </template>

    <script>
        function banglaOnly(input) {
            input.value = input.value.replace(/[^\u0980-\u09FF\s]/g, '');

            if (input.id === 'village_name') {
                updateAddressPreview();
            }
        }

        function updateAddressPreview() {
            const area = document.getElementById('area_name').value || 'ইউনিয়ন/পৌরসভা';
            const village = document.getElementById('village_name').value || 'গ্রামের নাম';
            document.getElementById('address_preview').textContent = area + ' | গ্রাম: ' + village;
        }

        function fillEmptyProblems() {
            document.querySelectorAll('input[name="initial_problem[]"]').forEach((input) => {
                if (input.value.trim() === '') {
                    input.value = 'নাই।';
                }
            });
        }

        function handleProblemEnter(event, input) {
            if (event.key !== 'Enter') {
                return;
            }

            event.preventDefault();

            if (input.value.trim() === '') {
                input.value = 'নাই।';
            }

            addMemberRow();
        }

        function addMemberRow() {
            const container = document.getElementById('member_container');
            const template = document.getElementById('member_template');

            container.appendChild(template.content.cloneNode(true));
            updateMemberRows();

            const rows = container.querySelectorAll('.member-row');
            const lastRow = rows[rows.length - 1];

            lastRow.scrollIntoView({ behavior: 'smooth', block: 'center' });
            lastRow.querySelector('input[name="member_name[]"]').focus();
        }

        function removeMemberRow(button) {
            const rows = document.querySelectorAll('.member-row');

            if (rows.length <= 1) {
                alert('কমপক্ষে একজন সদস্য রাখতে হবে।');
                return;
            }

            button.closest('.member-row').remove();
            updateMemberRows();
        }

        function updateMemberRows() {
            const rows = document.querySelectorAll('.member-row');

            rows.forEach((row, index) => {
                const number = index + 1;
                const numberEl = row.querySelector('.member-number');
                const titleEl = row.querySelector('.member-title');
                const deleteBtn = row.querySelector('button[onclick="removeMemberRow(this)"]');

                if (numberEl) numberEl.textContent = number;
                if (titleEl) titleEl.textContent = 'সদস্য ' + number;

                if (deleteBtn) {
                    deleteBtn.classList.toggle('hidden', rows.length === 1 && index === 0);
                }
            });
        }

        document.getElementById('area_name').addEventListener('change', updateAddressPreview);
        document.getElementById('village_name').addEventListener('input', updateAddressPreview);

        updateAddressPreview();
        updateMemberRows();
    </script>

</body>
</html>