<?php
require_once '../auth.php';

restore_login_from_cookie();

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

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

if (!function_exists('initial_letter')) {
    function initial_letter($value) {
        $value = trim((string) $value);
        if ($value === '') return 'A';
        return function_exists('mb_substr') ? mb_substr($value, 0, 1, 'UTF-8') : substr($value, 0, 1);
    }
}

function split_address_display($address) {
    $address = trim((string) $address);

    $data = [
        'area' => '',
        'village' => '',
        'full' => $address
    ];

    if (preg_match('/^(.*?)\s*\|\s*গ্রাম:\s*(.*)$/u', $address, $matches)) {
        $data['area'] = trim($matches[1]);
        $data['village'] = trim($matches[2]);
    }

    return $data;
}

function discount_info($total_visits) {
    $total_visits = (int) $total_visits;

    if ($total_visits <= 2) {
        return [
            'percent' => 25,
            'label' => '০ থেকে ২ ভিজিট'
        ];
    }

    if ($total_visits <= 5) {
        return [
            'percent' => 27,
            'label' => '৩ থেকে ৫ ভিজিট'
        ];
    }

    return [
        'percent' => 30,
        'label' => '৫ বারের বেশি ভিজিট'
    ];
}

$patient = null;
$family_members = [];
$visit_members = [];
$call_history = []; // নতুন যুক্ত করা হয়েছে
$error = "";
$search_query = trim($_GET['search_query'] ?? "");
$total_visits = 0;
$discount = discount_info(0);

if ($search_query !== "") {
    $normalized_search = strtoupper(str_replace([' ', '-'], '', $search_query));
    $card_like = '%' . $search_query . '%';

    $stmt = $conn->prepare("
        SELECT p.*, u.full_name AS officer_name
        FROM agh_patients p
        LEFT JOIN agh_users u ON p.marketing_officer_id = u.id
        WHERE
            p.mobile = ?
            OR p.card_number = ?
            OR REPLACE(REPLACE(UPPER(p.card_number), ' ', ''), '-', '') = ?
            OR p.card_number LIKE ?
        LIMIT 1
    ");
    $stmt->bind_param("ssss", $search_query, $search_query, $normalized_search, $card_like);

    $stmt->execute();
    $result = $stmt->get_result();

    if ($result && $result->num_rows > 0) {
        $patient = $result->fetch_assoc();
        $patient_id = (int) $patient['id'];

        $member_stmt = $conn->prepare("
            SELECT id, member_name, age, initial_problem
            FROM agh_family_members
            WHERE patient_id = ?
            ORDER BY id ASC
        ");
        $member_stmt->bind_param("i", $patient_id);
        $member_stmt->execute();
        $member_result = $member_stmt->get_result();

        while ($row = $member_result->fetch_assoc()) {
            $family_members[] = $row;
        }

        $member_stmt->close();

        $visit_stmt = $conn->prepare("
            SELECT COUNT(v.id) AS total_visits
            FROM agh_family_members m
            LEFT JOIN agh_visits v ON v.member_id = m.id
            WHERE m.patient_id = ?
        ");
        $visit_stmt->bind_param("i", $patient_id);
        $visit_stmt->execute();
        $visit_result = $visit_stmt->get_result();

        if ($visit_result && $visit_row = $visit_result->fetch_assoc()) {
            $total_visits = (int) $visit_row['total_visits'];
        }

        $visit_stmt->close();

        $visit_member_stmt = $conn->prepare("
            SELECT
                m.id,
                m.member_name,
                m.age,
                COUNT(v.id) AS visit_count,
                MAX(v.visit_date) AS last_visit
            FROM agh_family_members m
            LEFT JOIN agh_visits v ON v.member_id = m.id
            WHERE m.patient_id = ?
            GROUP BY m.id, m.member_name, m.age
            ORDER BY visit_count DESC, m.id ASC
        ");
        $visit_member_stmt->bind_param("i", $patient_id);
        $visit_member_stmt->execute();
        $visit_member_result = $visit_member_stmt->get_result();

        if ($visit_member_result) {
            while ($row = $visit_member_result->fetch_assoc()) {
                $visit_members[] = $row;
            }
        }

        $visit_member_stmt->close();

        // --- নতুন যুক্ত করা অংশ: কল হিস্ট্রি ডাটাবেস থেকে আনা ---
        $call_stmt = $conn->prepare("
            SELECT c.*, m.member_name, u.full_name as caller_name 
            FROM agh_call_logs c
            JOIN agh_family_members m ON c.member_id = m.id
            JOIN agh_users u ON c.user_id = u.id
            WHERE m.patient_id = ?
            ORDER BY c.created_at DESC
        ");
        $call_stmt->bind_param("i", $patient_id);
        $call_stmt->execute();
        $call_result = $call_stmt->get_result();
        
        if ($call_result) {
            while ($row = $call_result->fetch_assoc()) {
                $call_history[] = $row;
            }
        }
        $call_stmt->close();
        // ----------------------------------------------------

        $discount = discount_info($total_visits);
    } else {
        $error = "দুঃখিত, এই কার্ড নম্বর বা মোবাইল নম্বরে কোনো রোগী পাওয়া যায়নি।";
    }

    $stmt->close();
}

$member_count = count($family_members);
$address = $patient ? split_address_display($patient['address'] ?? '') : ['area' => '', 'village' => '', 'full' => ''];
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Patient Search - 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);
        }

        .label {
            font-size: 0.75rem;
            font-weight: 800;
            letter-spacing: 0.08em;
            text-transform: uppercase;
            color: #94a3b8;
        }
    </style>
</head>

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

    <nav class="sticky top-0 z-50 border-b border-white/70 glass shadow-sm">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
            <div class="flex items-center justify-between gap-4">
                <div class="flex items-center gap-6">
                    <a href="index.php" class="flex items-center gap-3">
                        <div class="h-12 w-12 rounded-2xl bg-gradient-to-br from-sky-700 to-emerald-500 text-white flex items-center justify-center font-extrabold shadow-lg shadow-sky-200">
                            AGH
                        </div>
                        <div>
                            <h1 class="text-lg sm:text-xl font-extrabold text-slate-900">AGH Admin</h1>
                            <p class="text-xs text-slate-500">Health Card Management</p>
                        </div>
                    </a>

                    <div class="hidden md:flex items-center gap-2">
                        <a href="index.php" class="rounded-full bg-sky-600 text-white px-4 py-2 text-sm font-bold shadow-lg shadow-sky-100">
                            রোগী সার্চ
                        </a>
                        
                        <!-- নতুন ফলো-আপ বাটন যুক্ত করা হয়েছে -->
                        <a href="follow_up.php" class="rounded-full bg-white border border-slate-100 text-slate-600 hover:text-sky-700 hover:bg-sky-50 px-4 py-2 text-sm font-bold transition">
                            ফলো-আপ ড্যাশবোর্ড
                        </a>

                        <a href="users.php" class="rounded-full bg-white border border-slate-100 text-slate-600 hover:text-sky-700 hover:bg-sky-50 px-4 py-2 text-sm font-bold transition">
                            অফিসার ম্যানেজমেন্ট
                        </a>
                        
                        <a href="total_report.php" class="rounded-full bg-white border border-slate-100 text-slate-600 hover:text-sky-700 hover:bg-sky-50 px-4 py-2 text-sm font-bold transition">
                            সকল রিপোর্ট
                        </a>
                    </div>
                </div>

                <a href="../logout.php" class="inline-flex items-center gap-2 rounded-full bg-red-500 hover:bg-red-600 text-white px-4 py-2 text-sm font-bold transition shadow-lg shadow-red-100">
                    লগআউট
                </a>
            </div>
        </div>
    </nav>

    <main class="max-w-7xl 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-800 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 grid lg:grid-cols-[1fr_420px] gap-8 items-end">
                <div>
                    <p class="text-sm font-semibold uppercase tracking-[0.28em] text-sky-100">Patient Lookup</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">
                        কার্ড নম্বর অথবা মোবাইল নম্বর দিয়ে রোগী, ঠিকানা, পরিবার, ভিজিট ও ডিসকাউন্ট দেখুন।
                    </p>
                </div>

                <form action="" method="GET" class="rounded-3xl bg-white/15 border border-white/20 p-4 shadow-xl">
                    <label for="search_query" class="block text-sm font-bold text-sky-50 mb-2">কার্ড / মোবাইল নম্বর</label>
                    <div class="flex flex-col sm:flex-row gap-3">
                        <input
                            id="search_query"
                            type="text"
                            name="search_query"
                            required
                            value="<?php echo e($search_query); ?>"
                            placeholder="যেমন: AGH 2501"
                            class="flex-1 rounded-2xl border border-white/30 bg-white/95 px-5 py-4 text-slate-900 placeholder:text-slate-400 outline-none focus:ring-4 focus:ring-white/20">

                        <button type="submit" class="inline-flex items-center justify-center gap-2 rounded-2xl bg-slate-950 hover:bg-slate-900 px-6 py-4 font-extrabold text-white transition active:scale-95">
                            সার্চ
                        </button>
                    </div>
                </form>
            </div>
        </section>

        <?php if ($error): ?>
            <div class="mb-8 rounded-3xl border border-red-200 bg-red-50 px-5 py-4 text-red-700 font-bold">
                <?php echo e($error); ?>
            </div>
        <?php endif; ?>

        <?php if ($patient): ?>
            <section class="grid grid-cols-1 lg:grid-cols-3 gap-7">

                <aside class="panel rounded-[2rem] p-6 h-fit">
                    <div class="flex items-center gap-3 mb-6">
                        <div class="h-12 w-12 rounded-2xl bg-sky-100 text-sky-700 flex items-center justify-center">
                            <svg width="26" height="26" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                                <path d="M20 21a8 8 0 0 0-16 0"></path>
                                <circle cx="12" cy="7" r="4"></circle>
                            </svg>
                        </div>
                        <div>
                            <h3 class="text-xl font-extrabold text-slate-900">রোগীর কার্ড</h3>
                            <p class="text-sm text-slate-500">কার্ড, ঠিকানা ও ডিসকাউন্ট</p>
                        </div>
                    </div>

                    <div class="space-y-5">
                        <div class="rounded-3xl bg-sky-50 border border-sky-100 p-5">
                            <p class="label">কার্ড নম্বর</p>
                            <p class="mt-2 text-2xl font-extrabold text-sky-700"><?php echo e($patient['card_number']); ?></p>
                        </div>

                        <div class="grid grid-cols-2 gap-4">
                            <button
                                type="button"
                                onclick="showVisitModal()"
                                class="w-full text-left rounded-3xl bg-slate-50 hover:bg-sky-50 border border-slate-100 hover:border-sky-200 p-5 transition">
                                <p class="label">মোট ভিজিট</p>
                                <p class="mt-2 text-3xl font-extrabold text-slate-900"><?php echo e($total_visits); ?></p>
                                <p class="mt-2 text-xs font-bold text-sky-600">বিস্তারিত দেখুন</p>
                            </button>

                            <div class="rounded-3xl bg-amber-50 border border-amber-100 p-5">
                                <p class="label text-amber-500">ডিসকাউন্ট</p>
                                <p class="mt-2 text-3xl font-extrabold text-amber-600"><?php echo e($discount['percent']); ?>%</p>
                            </div>
                        </div>

                        <div class="rounded-3xl bg-emerald-50 border border-emerald-100 p-5">
                            <p class="label text-emerald-500">Discount Rule</p>
                            <p class="mt-2 font-extrabold text-emerald-800"><?php echo e($discount['label']); ?></p>
                            <p class="mt-2 text-sm font-semibold text-slate-500">
                                এই কার্ডের সব সদস্যের মোট ভিজিট হিসাব করা হয়েছে।
                            </p>
                        </div>

                        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-1 gap-4">
                            <div class="rounded-3xl bg-slate-50 border border-slate-100 p-5">
                                <div class="flex items-start justify-between gap-3">
                                    <div>
                                        <p class="label">মোবাইল</p>
                                        <p id="patientMobile" class="mt-2 font-extrabold text-slate-800"><?php echo e($patient['mobile']); ?></p>
                                    </div>

                                    <button
                                        type="button"
                                        onclick="copyPatientMobile()"
                                        class="rounded-xl bg-white border border-slate-200 px-3 py-2 text-xs font-extrabold text-sky-700 hover:bg-sky-50 transition">
                                        Copy
                                    </button>
                                </div>
                            </div>

                            <div class="rounded-3xl bg-slate-50 border border-slate-100 p-5">
                                <p class="label">সদস্য সংখ্যা</p>
                                <p class="mt-2 font-extrabold text-emerald-700"><?php echo e($member_count); ?> জন</p>
                            </div>
                        </div>

                        <div class="rounded-3xl bg-indigo-50 border border-indigo-100 p-5">
                            <p class="label text-indigo-500">ঠিকানা</p>

                            <?php if ($address['area'] !== '' || $address['village'] !== ''): ?>
                                <div class="mt-3 space-y-3">
                                    <div class="rounded-2xl bg-white border border-indigo-100 px-4 py-3">
                                        <p class="text-xs font-extrabold text-slate-400">ইউনিয়ন / পৌরসভা</p>
                                        <p class="mt-1 font-extrabold text-indigo-800"><?php echo e($address['area']); ?></p>
                                    </div>

                                    <div class="rounded-2xl bg-white border border-indigo-100 px-4 py-3">
                                        <p class="text-xs font-extrabold text-slate-400">গ্রাম</p>
                                        <p class="mt-1 font-extrabold text-slate-800"><?php echo e($address['village']); ?></p>
                                    </div>
                                </div>
                            <?php elseif ($address['full'] !== ''): ?>
                                <p class="mt-2 text-slate-700 leading-7"><?php echo e($address['full']); ?></p>
                            <?php else: ?>
                                <p class="mt-2 text-slate-400 font-semibold">ঠিকানা দেওয়া হয়নি</p>
                            <?php endif; ?>
                        </div>

                        <div class="rounded-3xl bg-cyan-50 border border-cyan-100 p-5">
                            <p class="label text-cyan-600">রেজিস্ট্রেশনের তারিখ</p>
                            <p class="mt-2 font-extrabold text-cyan-900 flex flex-wrap items-center gap-2">
                                <?php if (!empty($patient['reg_date'])): ?>
                                    <span><?php echo e(date('d F, Y', strtotime($patient['reg_date']))); ?></span>
                                    <span class="rounded-lg bg-cyan-100 px-2 py-1 text-xs font-bold text-cyan-700">
                                        <?php echo e(date('h:i A', strtotime($patient['reg_date']))); ?>
                                    </span>
                                <?php else: ?>
                                    <span class="text-slate-400 font-semibold">তারিখ দেওয়া নেই</span>
                                <?php endif; ?>
                            </p>
                        </div>

                        <div class="rounded-3xl bg-emerald-50 border border-emerald-100 p-5">
                            <p class="label text-emerald-500">রেজিস্ট্রেশন অফিসার</p>
                            <p class="mt-2 font-extrabold text-emerald-800">
                                <?php echo e($patient['officer_name'] ?? 'সিস্টেম এডমিন'); ?>
                            </p>
                        </div>
                    </div>
                </aside>

                <!-- এখানে একটি Wrapper Div তৈরি করা হয়েছে যেন Family Member এবং Call History পরপর বসে -->
                <div class="lg:col-span-2 flex flex-col gap-7">
                    
                    <!-- Family Members Section -->
                    <section class="panel rounded-[2rem] overflow-hidden">
                        <div class="p-6 sm:p-7 border-b border-slate-100 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                            <div>
                                <p class="text-sm font-bold text-sky-600">Family Members</p>
                                <h3 class="mt-1 text-2xl font-extrabold text-slate-900">পরিবারের সদস্যবৃন্দ</h3>
                            </div>

                            <span class="inline-flex items-center justify-center rounded-full bg-slate-100 text-slate-700 px-4 py-2 text-sm font-extrabold">
                                <?php echo e($member_count); ?> জন সদস্য
                            </span>
                        </div>

                        <div class="overflow-x-auto">
                            <table class="w-full text-left">
                                <thead>
                                    <tr class="bg-slate-50 text-slate-500 text-xs uppercase tracking-wider">
                                        <th class="px-6 py-4 font-extrabold">সদস্য</th>
                                        <th class="px-6 py-4 font-extrabold">বয়স</th>
                                        <th class="px-6 py-4 font-extrabold">সমস্যা</th>
                                        <th class="px-6 py-4 font-extrabold text-right">অ্যাকশন</th>
                                    </tr>
                                </thead>

                                <tbody class="divide-y divide-slate-100">
                                    <?php foreach ($family_members as $mem): ?>
                                        <tr class="hover:bg-sky-50/60 transition">
                                            <td class="px-6 py-5">
                                                <div class="flex items-center gap-3">
                                                    <div class="h-11 w-11 rounded-2xl bg-sky-100 text-sky-700 flex items-center justify-center font-extrabold">
                                                        <?php echo e(initial_letter($mem['member_name'])); ?>
                                                    </div>
                                                    <div>
                                                        <p class="font-extrabold text-slate-900"><?php echo e($mem['member_name']); ?></p>
                                                        <p class="text-xs text-slate-400 mt-1">ID: #<?php echo str_pad((string) $mem['id'], 4, '0', STR_PAD_LEFT); ?></p>
                                                    </div>
                                                </div>
                                            </td>

                                            <td class="px-6 py-5 font-bold text-slate-700">
                                                <?php echo e($mem['age']); ?> বছর
                                            </td>

                                            <td class="px-6 py-5 text-slate-600">
                                                <?php echo !empty($mem['initial_problem']) ? e($mem['initial_problem']) : '<span class="text-slate-400">উল্লেখ নেই</span>'; ?>
                                            </td>

                                            <td class="px-6 py-5 text-right">
                                                <a href="visit_entry.php?member_id=<?php echo e($mem['id']); ?>" class="inline-flex items-center justify-center gap-2 rounded-2xl bg-emerald-500 hover:bg-emerald-600 text-white px-5 py-3 text-sm font-extrabold shadow-lg shadow-emerald-100 transition">
                                                    নতুন ভিজিট
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>

                                    <?php if ($member_count === 0): ?>
                                        <tr>
                                            <td colspan="4" class="px-6 py-14 text-center">
                                                <h4 class="text-lg font-extrabold text-slate-700">কোনো সদস্য পাওয়া যায়নি</h4>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </section>

                    <!-- নতুন যুক্ত করা অংশ: Call History Section -->
                    <section class="panel rounded-[2rem] overflow-hidden">
                        <div class="p-6 sm:p-7 border-b border-slate-100 bg-indigo-50/50 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                            <div>
                                <p class="text-sm font-bold text-indigo-600">Communication History</p>
                                <h3 class="mt-1 text-2xl font-extrabold text-slate-900">যোগাযোগের ইতিহাস</h3>
                            </div>
                            <span class="inline-flex items-center justify-center rounded-full bg-indigo-100 text-indigo-700 px-4 py-2 text-sm font-extrabold">
                                <?php echo count($call_history); ?> টি কল
                            </span>
                        </div>

                        <div class="p-6 sm:p-7">
                            <?php if (count($call_history) > 0): ?>
                                <div class="space-y-4">
                                    <?php foreach ($call_history as $log): ?>
                                        <div class="rounded-3xl border border-slate-100 bg-slate-50 p-5 hover:bg-indigo-50/30 transition">
                                            <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-2 mb-3">
                                                <div class="flex items-center gap-3">
                                                    <div class="h-10 w-10 rounded-xl bg-indigo-100 text-indigo-600 flex items-center justify-center text-lg">📞</div>
                                                    <div>
                                                        <p class="font-extrabold text-slate-900"><?php echo e($log['member_name']); ?></p>
                                                        <p class="text-xs font-bold text-slate-500"><?php echo date('d M, Y | h:i A', strtotime($log['created_at'])); ?></p>
                                                    </div>
                                                </div>
                                                <span class="px-3 py-1 rounded-lg text-xs font-bold <?php echo $log['call_status'] == 'Answered' ? 'bg-emerald-100 text-emerald-700' : 'bg-amber-100 text-amber-700'; ?>">
                                                    <?php echo e($log['call_status']); ?>
                                                </span>
                                            </div>
                                            
                                            <?php if(!empty($log['call_note'])): ?>
                                                <p class="text-sm text-slate-600 bg-white p-4 rounded-2xl border border-slate-100 mb-3"><?php echo nl2br(e($log['call_note'])); ?></p>
                                            <?php endif; ?>

                                            <div class="flex flex-wrap items-center justify-between gap-2 text-xs font-semibold text-slate-500 border-t border-slate-100 pt-3">
                                                <p>অফিসার: <span class="font-bold text-slate-700"><?php echo e($log['caller_name']); ?></span></p>
                                                <?php if($log['next_followup_date']): ?>
                                                    <p class="text-amber-600 bg-amber-50 px-2 py-1 rounded-md">নেক্সট কল: <?php echo date('d M, Y', strtotime($log['next_followup_date'])); ?></p>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <div class="text-center py-10">
                                    <div class="h-16 w-16 mx-auto rounded-full bg-slate-100 text-slate-400 flex items-center justify-center text-2xl mb-4">📞</div>
                                    <h4 class="text-lg font-extrabold text-slate-700">এই রোগীকে এখনো কল দেওয়া হয়নি</h4>
                                    <p class="text-sm text-slate-500 mt-1">ফলো-আপ ড্যাশবোর্ড থেকে কল করে নোট যুক্ত করুন।</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </section>
                </div> <!-- End of lg:col-span-2 wrapper -->

            </section>
        <?php elseif ($search_query === "" && !$error): ?>
            <section class="panel rounded-[2rem] p-8 sm:p-10 text-center">
                <h3 class="text-2xl font-extrabold text-slate-900">সার্চ শুরু করুন</h3>
                <p class="mt-3 text-slate-500">উপরের বক্সে কার্ড নম্বর অথবা মোবাইল নম্বর লিখে রোগীর তথ্য দেখুন।</p>
            </section>
        <?php endif; ?>

    </main>

    <?php if ($patient): ?>
        <div id="visitModal" class="fixed inset-0 z-[70] hidden items-center justify-center bg-slate-950/60 p-4 backdrop-blur-sm">
            <div class="w-full max-w-2xl rounded-[2rem] bg-white shadow-2xl overflow-hidden">
                <div class="flex items-center justify-between gap-4 border-b border-slate-100 p-5 sm:p-6">
                    <div>
                        <p class="text-sm font-bold text-sky-600">Visit Details</p>
                        <h3 class="mt-1 text-2xl font-extrabold text-slate-900">কে কতবার এসেছে</h3>
                        <p class="mt-1 text-sm text-slate-500">
                            কার্ড: <?php echo e($patient['card_number']); ?>
                        </p>
                    </div>

                    <button type="button" onclick="hideVisitModal()" class="h-10 w-10 rounded-2xl bg-slate-100 hover:bg-slate-200 text-slate-600 flex items-center justify-center transition">
                        <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24">
                            <path d="M18 6 6 18"></path>
                            <path d="m6 6 12 12"></path>
                        </svg>
                    </button>
                </div>

                <div class="max-h-[70vh] overflow-y-auto p-5 sm:p-6">
                    <?php if (count($visit_members) > 0): ?>
                        <div class="space-y-3">
                            <?php foreach ($visit_members as $row): ?>
                                <div class="rounded-3xl border border-slate-100 bg-slate-50 p-4 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                                    <div class="flex items-center gap-3">
                                        <div class="h-11 w-11 rounded-2xl bg-sky-100 text-sky-700 flex items-center justify-center font-extrabold">
                                            <?php echo e(initial_letter($row['member_name'])); ?>
                                        </div>

                                        <div>
                                            <p class="font-extrabold text-slate-900"><?php echo e($row['member_name']); ?></p>
                                            <p class="text-xs font-semibold text-slate-400">
                                                বয়স: <?php echo e($row['age']); ?> বছর
                                            </p>
                                            <p class="mt-1 text-xs font-semibold text-slate-500">
                                                শেষ ভিজিট:
                                                <?php echo !empty($row['last_visit']) ? e(date('d M, Y | h:i A', strtotime($row['last_visit']))) : 'এখনো আসেনি'; ?>
                                            </p>
                                        </div>
                                    </div>

                                    <div class="rounded-2xl bg-white border border-slate-100 px-5 py-3 text-center">
                                        <p class="text-3xl font-extrabold text-emerald-600"><?php echo e($row['visit_count']); ?></p>
                                        <p class="text-xs font-extrabold text-slate-400">বার এসেছে</p>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="py-12 text-center">
                            <h4 class="text-lg font-extrabold text-slate-700">কোনো সদস্য পাওয়া যায়নি</h4>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    <?php endif; ?>
    
    <script>
    function copyPatientMobile() {
        const mobileEl = document.getElementById('patientMobile');
        const toast = document.getElementById('copyToast');

        if (!mobileEl) return;

        const text = mobileEl.textContent.trim();

        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(text).then(function() {
                showCopyToast(toast);
            });
        } else {
            const input = document.createElement('textarea');
            input.value = text;
            input.style.position = 'fixed';
            input.style.opacity = '0';
            document.body.appendChild(input);
            input.focus();
            input.select();
            document.execCommand('copy');
            input.remove();
            showCopyToast(toast);
        }
    }

    function showCopyToast(toast) {
        if (!toast) return;

        toast.classList.remove('hidden');

        clearTimeout(window.copyToastTimer);
        window.copyToastTimer = setTimeout(function() {
            toast.classList.add('hidden');
        }, 1300);
    }
    </script>

    <script>
        function showVisitModal() {
            const modal = document.getElementById('visitModal');
            if (!modal) return;

            modal.classList.remove('hidden');
            modal.classList.add('flex');
        }

        function hideVisitModal() {
            const modal = document.getElementById('visitModal');
            if (!modal) return;

            modal.classList.add('hidden');
            modal.classList.remove('flex');
        }

        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                hideVisitModal();
            }
        });

        document.addEventListener('click', function(event) {
            const modal = document.getElementById('visitModal');
            if (modal && event.target === modal) {
                hideVisitModal();
            }
        });
    </script>
    
    <div id="copyToast" class="fixed bottom-5 left-1/2 z-[90] hidden -translate-x-1/2 rounded-full bg-slate-950 px-5 py-3 text-sm font-extrabold text-white shadow-2xl">
        Copied
    </div>

</body>
</html>