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

$message = [
    'type' => '',
    'text' => ''
];

function set_message(&$message, $type, $text) {
    $message['type'] = $type;
    $message['text'] = $text;
}

$conn->query("
    CREATE TABLE IF NOT EXISTS agh_doctors (
        id INT AUTO_INCREMENT PRIMARY KEY,
        doctor_name VARCHAR(100) NOT NULL
    )
");

$check_col = $conn->query("SHOW COLUMNS FROM agh_visits LIKE 'doctor_id'");
if ($check_col && $check_col->num_rows === 0) {
    $conn->query("ALTER TABLE agh_visits ADD COLUMN doctor_id INT AFTER member_id");
}

$member_id = (int) ($_GET['member_id'] ?? 0);

if (isset($_POST['add_new_doctor'])) {
    $doctor_name = trim($_POST['doctor_name'] ?? '');

    if ($doctor_name === '') {
        set_message($message, 'error', 'ডাক্তারের নাম লিখুন।');
    } else {
        $stmt = $conn->prepare("INSERT INTO agh_doctors (doctor_name) VALUES (?)");
        $stmt->bind_param("s", $doctor_name);

        if ($stmt->execute()) {
            set_message($message, 'success', 'নতুন ডাক্তার সফলভাবে যোগ হয়েছে।');
        } else {
            set_message($message, 'error', 'ডাক্তার যোগ করা যায়নি।');
        }

        $stmt->close();
    }
}

$stmt = $conn->prepare("
    SELECT m.*, p.mobile, p.card_number
    FROM agh_family_members m
    JOIN agh_patients p ON m.patient_id = p.id
    WHERE m.id = ?
    LIMIT 1
");
$stmt->bind_param("i", $member_id);
$stmt->execute();
$member_result = $stmt->get_result();
$member = $member_result ? $member_result->fetch_assoc() : null;
$stmt->close();

if (!$member) {
    die("সদস্য খুঁজে পাওয়া যায়নি!");
}

if (isset($_POST['save_visit'])) {
    $problem = trim($_POST['current_problem'] ?? '');
    $doctor_id = (int) ($_POST['doctor_id'] ?? 0);
    $visit_date = date('Y-m-d H:i:s');

    if ($doctor_id <= 0 || $problem === '') {
        set_message($message, 'error', 'ডাক্তার এবং বর্তমান সমস্যা নির্বাচন করুন।');
    } else {
        $stmt = $conn->prepare("
            INSERT INTO agh_visits (member_id, doctor_id, visit_date, current_problem)
            VALUES (?, ?, ?, ?)
        ");
        $stmt->bind_param("iiss", $member_id, $doctor_id, $visit_date, $problem);

        if ($stmt->execute()) {
            set_message($message, 'success', 'ভিজিট সফলভাবে এন্ট্রি হয়েছে।');
        } else {
            set_message($message, 'error', 'ভিজিট সেভ করা যায়নি।');
        }

        $stmt->close();
    }
}

$doctors = [];
$result = $conn->query("SELECT id, doctor_name FROM agh_doctors ORDER BY doctor_name ASC");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $doctors[] = $row;
    }
}

$history = [];
$stmt = $conn->prepare("
    SELECT v.*, d.doctor_name
    FROM agh_visits v
    LEFT JOIN agh_doctors d ON v.doctor_id = d.id
    WHERE v.member_id = ?
    ORDER BY v.visit_date DESC
");
$stmt->bind_param("i", $member_id);
$stmt->execute();
$history_result = $stmt->get_result();

if ($history_result) {
    while ($row = $history_result->fetch_assoc()) {
        $history[] = $row;
    }
}

$stmt->close();

$visit_count = count($history);
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Visit Entry - 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.95);
            padding: 0.9rem 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);
        }

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

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

        .modal {
            background: rgba(15, 23, 42, 0.62);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
        }
    </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-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
            <div class="flex items-center justify-between gap-4">
                <a href="index.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 Admin Panel</p>
                </div>
            </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 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">Visit Entry</p>
                    <h2 class="mt-4 text-3xl sm:text-5xl font-extrabold leading-tight"><?php echo e($member['member_name']); ?></h2>
                    <p class="mt-4 max-w-2xl text-sky-50 leading-8">
                        রোগীর বর্তমান সমস্যা, ডাক্তার এবং পূর্বের ভিজিট হিস্ট্রি একসাথে ম্যানেজ করুন।
                    </p>
                </div>

                <div class="grid grid-cols-2 gap-3 min-w-full sm:min-w-[320px]">
                    <div class="rounded-3xl bg-white/15 border border-white/20 p-5">
                        <p class="text-sm font-bold text-sky-100">কার্ড নম্বর</p>
                        <p class="mt-2 text-2xl font-extrabold"><?php echo e($member['card_number']); ?></p>
                    </div>
                    <div class="rounded-3xl bg-white/15 border border-white/20 p-5">
                        <p class="text-sm font-bold text-sky-100">ভিজিট</p>
                        <p class="mt-2 text-2xl font-extrabold"><?php echo e($visit_count); ?></p>
                    </div>
                </div>
            </div>
        </section>

        <?php if ($message['text'] !== ''): ?>
            <div class="mb-6 rounded-3xl border px-5 py-4 font-bold flex items-center gap-3 <?php echo $message['type'] === 'success' ? 'border-emerald-200 bg-emerald-50 text-emerald-800' : 'border-red-200 bg-red-50 text-red-700'; ?>">
                <span class="h-10 w-10 rounded-2xl flex items-center justify-center <?php echo $message['type'] === 'success' ? 'bg-emerald-100' : 'bg-red-100'; ?>">
                    <?php if ($message['type'] === 'success'): ?>
                        <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>
                    <?php else: ?>
                        <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>
                    <?php endif; ?>
                </span>
                <?php echo e($message['text']); ?>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">

            <aside class="space-y-6">
                <section class="panel rounded-[2rem] p-6">
                    <div class="flex items-center gap-4">
                        <div class="h-16 w-16 rounded-3xl bg-sky-100 text-sky-700 flex items-center justify-center text-2xl font-extrabold">
                            <?php echo e(initial_letter($member['member_name'])); ?>
                        </div>
                        <div>
                            <h3 class="text-2xl font-extrabold text-slate-900"><?php echo e($member['member_name']); ?></h3>
                            <p class="text-sm text-slate-500 mt-1">কার্ড: <?php echo e($member['card_number']); ?></p>
                        </div>
                    </div>

                    <div class="grid grid-cols-2 gap-3 mt-6">
                        <div class="rounded-3xl bg-slate-50 border border-slate-100 p-4">
                            <p class="meta-label">মোবাইল</p>
                            <p class="mt-2 font-extrabold text-slate-800"><?php echo e($member['mobile']); ?></p>
                        </div>
                        <div class="rounded-3xl bg-slate-50 border border-slate-100 p-4">
                            <p class="meta-label">বয়স</p>
                            <p class="mt-2 font-extrabold text-slate-800"><?php echo e($member['age']); ?> বছর</p>
                        </div>
                    </div>

                    <?php if (!empty($member['initial_problem'])): ?>
                        <div class="mt-3 rounded-3xl bg-amber-50 border border-amber-100 p-4">
                            <p class="meta-label text-amber-600">প্রাথমিক সমস্যা</p>
                            <p class="mt-2 text-slate-700 leading-7"><?php echo e($member['initial_problem']); ?></p>
                        </div>
                    <?php endif; ?>
                </section>

                <section class="panel rounded-[2rem] p-6">
                    <div class="flex items-center justify-between gap-4 mb-6">
                        <div>
                            <p class="text-sm font-bold text-sky-600">New Visit</p>
                            <h3 class="text-xl font-extrabold text-slate-900">ভিজিট তথ্য</h3>
                        </div>
                        <button type="button" onclick="showModal('docModal')" class="h-11 w-11 rounded-2xl bg-sky-100 hover:bg-sky-200 text-sky-700 flex items-center justify-center transition" title="নতুন ডাক্তার যোগ করুন">
                            <svg width="21" height="21" 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>

                    <form action="?member_id=<?php echo e($member_id); ?>" method="POST" class="space-y-4">
                        <div>
                            <label for="doctor_id" class="label">ডাক্তার সিলেক্ট করুন</label>
                            <select id="doctor_id" name="doctor_id" required class="field">
                                <option value="">ডাক্তার বেছে নিন</option>
                                <?php foreach ($doctors as $doctor): ?>
                                    <option value="<?php echo e($doctor['id']); ?>"><?php echo e($doctor['doctor_name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div>
                            <label for="current_problem" class="label">বর্তমান সমস্যা</label>
                            <textarea id="current_problem" name="current_problem" required rows="4" class="field resize-none" placeholder="সমস্যা লিখুন"></textarea>
                        </div>

                        <button type="submit" name="save_visit" class="w-full inline-flex items-center justify-center gap-2 rounded-2xl bg-gradient-to-r from-sky-600 to-emerald-500 px-5 py-4 font-extrabold text-white shadow-xl shadow-sky-100 transition hover:-translate-y-0.5 hover:shadow-2xl">
                            <svg width="19" height="19" fill="none" stroke="currentColor" stroke-width="2.4" viewBox="0 0 24 24">
                                <path d="M20 6 9 17l-5-5"></path>
                            </svg>
                            ভিজিট সেভ করুন
                        </button>
                    </form>
                </section>
            </aside>

            <section class="lg:col-span-2 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">Visit 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-slate-100 text-slate-700 px-4 py-2 text-sm font-extrabold">
                        <?php echo e($visit_count); ?>টি ভিজিট
                    </span>
                </div>

                <div class="p-5 sm:p-7">
                    <?php if ($visit_count > 0): ?>
                        <div class="space-y-4">
                            <?php foreach ($history as $row): ?>
                                <article class="rounded-3xl bg-slate-50 border border-slate-100 p-5 hover:bg-sky-50/70 transition">
                                    <div class="flex flex-col md:flex-row md:items-start md:justify-between gap-4">
                                        <div class="flex gap-4">
                                            <div class="h-12 w-12 rounded-2xl bg-sky-100 text-sky-700 flex items-center justify-center">
                                                <svg width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                                                    <path d="M8 2v4"></path>
                                                    <path d="M16 2v4"></path>
                                                    <rect x="3" y="4" width="18" height="18" rx="2"></rect>
                                                    <path d="M3 10h18"></path>
                                                </svg>
                                            </div>

                                            <div>
                                                <p class="text-sm font-extrabold text-sky-700">
                                                    <?php echo e(date('d M, Y | h:i A', strtotime($row['visit_date']))); ?>
                                                </p>
                                                <p class="mt-2 text-slate-800 leading-7 font-semibold">
                                                    <?php echo e($row['current_problem']); ?>
                                                </p>
                                            </div>
                                        </div>

                                        <div class="md:text-right rounded-2xl bg-white border border-slate-100 px-4 py-3 min-w-[180px]">
                                            <p class="meta-label">ডাক্তার</p>
                                            <p class="mt-1 text-sm font-extrabold text-slate-800">
                                                <?php echo e($row['doctor_name'] ?? 'N/A'); ?>
                                            </p>
                                        </div>
                                    </div>
                                </article>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="py-16 text-center">
                            <div class="mx-auto h-16 w-16 rounded-3xl bg-slate-100 text-slate-400 flex items-center justify-center mb-4">
                                <svg width="32" height="32" fill="none" stroke="currentColor" stroke-width="1.8" viewBox="0 0 24 24">
                                    <path d="M8 2v4"></path>
                                    <path d="M16 2v4"></path>
                                    <rect x="3" y="4" width="18" height="18" rx="2"></rect>
                                    <path d="M3 10h18"></path>
                                </svg>
                            </div>
                            <h4 class="text-lg font-extrabold text-slate-700">কোনো ভিজিট রেকর্ড নেই</h4>
                            <p class="mt-2 text-sm text-slate-400">নতুন ভিজিট সেভ করলে এখানে দেখা যাবে।</p>
                        </div>
                    <?php endif; ?>
                </div>
            </section>

        </div>
    </main>

    <div id="docModal" class="modal fixed inset-0 z-[60] hidden items-center justify-center p-4">
        <form action="?member_id=<?php echo e($member_id); ?>" method="POST" class="w-full max-w-md rounded-[2rem] bg-white p-6 shadow-2xl">
            <div class="flex items-center justify-between gap-4 mb-5">
                <div>
                    <p class="text-sm font-bold text-emerald-600">Doctor Setup</p>
                    <h3 class="text-2xl font-extrabold text-slate-900">নতুন ডাক্তার</h3>
                </div>

                <button type="button" onclick="hideModal('docModal')" 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>
                <label for="doctor_name" class="label">ডাক্তারের নাম</label>
                <input id="doctor_name" type="text" name="doctor_name" required class="field" placeholder="যেমন: ডাঃ রহিম">
            </div>

            <div class="grid grid-cols-2 gap-3 pt-5">
                <button type="button" onclick="hideModal('docModal')" class="rounded-2xl bg-slate-100 hover:bg-slate-200 px-5 py-3 font-extrabold text-slate-700 transition">
                    বাতিল
                </button>
                <button type="submit" name="add_new_doctor" class="rounded-2xl bg-emerald-500 hover:bg-emerald-600 px-5 py-3 font-extrabold text-white transition">
                    সেভ করুন
                </button>
            </div>
        </form>
    </div>

    <script>
        function showModal(id) {
            const modal = document.getElementById(id);
            modal.classList.remove('hidden');
            modal.classList.add('flex');
        }

        function hideModal(id) {
            const modal = document.getElementById(id);
            modal.classList.add('hidden');
            modal.classList.remove('flex');
        }

        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                hideModal('docModal');
            }
        });
    </script>

</body>
</html>
