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

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

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

$search_query = trim($_GET['q'] ?? "");
$search_results = [];
$today_reminders = [];

// আজকের ফলো-আপ রিমাইন্ডার বের করা (এখানে p.reg_date যোগ করা হয়েছে)
$today = date('Y-m-d');
$rem_stmt = $conn->prepare("
    SELECT c.id as log_id, c.call_note, m.id as member_id, m.member_name, m.age, p.mobile, p.card_number, p.reg_date 
    FROM agh_call_logs c
    JOIN agh_family_members m ON c.member_id = m.id
    JOIN agh_patients p ON m.patient_id = p.id
    WHERE c.next_followup_date = ?
    ORDER BY c.id DESC
");
$rem_stmt->bind_param("s", $today);
$rem_stmt->execute();
$rem_res = $rem_stmt->get_result();
while ($row = $rem_res->fetch_assoc()) {
    $today_reminders[] = $row;
}
$rem_stmt->close();

// রোগের নাম দিয়ে সার্চ করা (এখানেও p.reg_date যোগ করা হয়েছে)
if ($search_query !== "") {
    $like_query = '%' . $search_query . '%';
    $stmt = $conn->prepare("
        SELECT m.id as member_id, m.member_name, m.age, m.initial_problem, p.mobile, p.card_number, p.reg_date,
        (SELECT call_status FROM agh_call_logs WHERE member_id = m.id ORDER BY id DESC LIMIT 1) as last_status,
        (SELECT created_at FROM agh_call_logs WHERE member_id = m.id ORDER BY id DESC LIMIT 1) as last_called
        FROM agh_family_members m
        JOIN agh_patients p ON m.patient_id = p.id
        WHERE m.initial_problem LIKE ?
    ");
    $stmt->bind_param("s", $like_query);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $search_results[] = $row;
    }
    $stmt->close();
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Follow Up - AGH</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Bengali:wght@400;600;800&family=Poppins:wght@400;600;800&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Noto Sans Bengali', 'Poppins', sans-serif; }
        .page-bg { background: linear-gradient(135deg, #f8fafc 0%, #eff6ff 48%, #ecfdf5 100%); }
        .glass { background: rgba(255, 255, 255, 0.9); backdrop-filter: blur(18px); }
        .panel { background: rgba(255, 255, 255, 0.95); box-shadow: 0 10px 40px rgba(0,0,0,0.05); border-radius: 1.5rem; }
    </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 flex items-center justify-between">
            <div class="flex items-center gap-6">
                <a href="index.php" class="flex items-center gap-3">
                    <div class="h-10 w-10 rounded-xl bg-gradient-to-br from-sky-700 to-emerald-500 text-white flex items-center justify-center font-extrabold">AGH</div>
                    <h1 class="text-xl font-extrabold text-slate-900">ফলো-আপ ড্যাশবোর্ড</h1>
                </a>
                <div class="hidden md:flex items-center gap-2">
                    <a href="index.php" class="rounded-full bg-white text-slate-600 hover:bg-sky-50 px-4 py-2 text-sm font-bold transition border">রোগী সার্চ</a>
                    <a href="follow_up.php" class="rounded-full bg-indigo-600 text-white px-4 py-2 text-sm font-bold shadow-lg">ফলো-আপ</a>
                </div>
            </div>
            <a href="../logout.php" class="rounded-full bg-red-500 hover:bg-red-600 text-white px-4 py-2 text-sm font-bold transition shadow-lg">লগআউট</a>
        </div>
    </nav>

    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        
        <?php if(isset($_GET['success'])): ?>
            <div class="mb-6 p-4 bg-emerald-100 text-emerald-800 rounded-xl font-bold flex justify-between items-center">
                <span>কল লগ সফলভাবে সেভ হয়েছে!</span>
                <button onclick="this.parentElement.style.display='none'" class="text-emerald-900">&times;</button>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            
            <!-- Left Side: Search & Results -->
            <div class="lg:col-span-2 space-y-6">
                <section class="panel p-6 bg-gradient-to-r from-indigo-600 to-blue-600 text-white">
                    <h2 class="text-2xl font-extrabold">রোগীর সমস্যা লিখে সার্চ করুন</h2>
                    <p class="mt-2 text-indigo-100 text-sm">যেমন: ডায়া, ডায়াবেটিস, গ্যাস্ট্রিক ইত্যাদি লিখে রোগীদের লিস্ট বের করুন।</p>
                    <form action="" method="GET" class="mt-5 flex gap-3">
                        <input type="text" name="q" value="<?php echo e($search_query); ?>" placeholder="রোগের নাম লিখুন..." required class="flex-1 rounded-xl px-4 py-3 text-slate-900 outline-none focus:ring-4 focus:ring-white/30">
                        <button type="submit" class="bg-slate-900 text-white px-6 py-3 rounded-xl font-bold hover:bg-slate-800 transition">সার্চ</button>
                    </form>
                </section>

                <?php if ($search_query !== ""): ?>
                <section class="panel p-6">
                    <h3 class="text-xl font-extrabold text-slate-800 mb-4">সার্চ রেজাল্ট: <?php echo count($search_results); ?> জন রোগী</h3>
                    <div class="overflow-x-auto">
                        <table class="w-full text-left border-collapse">
                            <thead>
                                <tr class="bg-slate-50 text-slate-500 text-sm">
                                    <th class="px-4 py-3 font-bold">রোগীর বিবরণ</th>
                                    <th class="px-4 py-3 font-bold">সমস্যা ও স্ট্যাটাস</th>
                                    <th class="px-4 py-3 font-bold text-right">অ্যাকশন</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                                <?php foreach ($search_results as $mem): ?>
                                <tr>
                                    <td class="px-4 py-4">
                                        <p class="font-extrabold text-slate-900 text-lg"><?php echo e($mem['member_name']); ?> <span class="text-sm font-semibold text-slate-500">(<?php echo e($mem['age']); ?>)</span></p>
                                        <p class="text-sm text-slate-600 mt-1 flex items-center gap-1">📞 <?php echo e($mem['mobile']); ?></p>
                                        <p class="text-xs text-indigo-600 mt-1 font-bold bg-indigo-50 inline-block px-2 py-1 rounded">
                                            রেজিঃ <?php echo !empty($mem['reg_date']) ? date('d M, Y', strtotime($mem['reg_date'])) : 'জানা নেই'; ?>
                                        </p>
                                    </td>
                                    
                                    <td class="px-4 py-4 text-sm">
                                        <p class="text-slate-700 font-semibold mb-2"><?php echo e($mem['initial_problem']); ?></p>
                                        <?php if($mem['last_status'] == 'Answered'): ?> 
                                            <span class="text-emerald-600 bg-emerald-50 px-2 py-1 rounded text-xs font-bold border border-emerald-100">✅ কথা হয়েছে</span>
                                        <?php elseif($mem['last_status']): ?> 
                                            <span class="text-amber-600 bg-amber-50 px-2 py-1 rounded text-xs font-bold border border-amber-100"><?php echo e($mem['last_status']); ?></span>
                                        <?php else: ?> 
                                            <span class="text-slate-400 text-xs font-bold">কল করা হয়নি</span> 
                                        <?php endif; ?>
                                    </td>
                                    
                                    <td class="px-4 py-4">
                                        <div class="flex flex-col gap-2 items-end">
                                            <div class="flex gap-2">
                                                <a href="index.php?search_query=<?php echo urlencode($mem['card_number']); ?>" class="bg-slate-100 text-slate-600 hover:bg-slate-200 px-3 py-1.5 rounded-lg text-xs font-bold transition" title="রোগীর প্রোফাইল দেখুন">বিস্তারিত</a>
                                                <button onclick="openModal(<?php echo $mem['member_id']; ?>, '<?php echo e($mem['member_name']); ?>', '<?php echo e($mem['mobile']); ?>')" class="bg-indigo-100 text-indigo-700 hover:bg-indigo-600 hover:text-white px-3 py-1.5 rounded-lg text-xs font-bold transition">নোট লিখুন</button>
                                            </div>
                                            <div class="flex gap-2">
                                                <a href="sms:<?php echo e($mem['mobile']); ?>" class="bg-blue-50 text-blue-600 hover:bg-blue-100 border border-blue-100 px-3 py-1.5 rounded-lg text-xs font-bold transition">SMS</a>
                                                <a href="https://wa.me/<?php echo substr($mem['mobile'], 0, 2) === '88' ? $mem['mobile'] : '88'.$mem['mobile']; ?>" target="_blank" class="bg-emerald-50 text-emerald-600 hover:bg-emerald-100 border border-emerald-100 px-3 py-1.5 rounded-lg text-xs font-bold transition">WhatsApp</a>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </section>
                <?php endif; ?>
            </div>

            <!-- Right Side: Today's Reminders -->
            <aside class="space-y-6">
                <div class="panel p-6 border-t-4 border-amber-500">
                    <h3 class="text-lg font-extrabold text-slate-900 flex justify-between items-center">
                        আজকের ফলো-আপ 
                        <span class="bg-amber-100 text-amber-700 px-3 py-1 rounded-full text-sm"><?php echo count($today_reminders); ?></span>
                    </h3>
                    
                    <div class="mt-5 space-y-4">
                        <?php if(count($today_reminders) > 0): ?>
                            <?php foreach($today_reminders as $rem): ?>
                            <div class="p-4 bg-slate-50 rounded-2xl border border-slate-100 hover:shadow-md transition">
                                <p class="font-extrabold text-slate-800 text-lg"><?php echo e($rem['member_name']); ?> <span class="text-sm font-semibold text-slate-500">(<?php echo e($rem['age']); ?>)</span></p>
                                <p class="text-sm font-mono text-slate-600 mt-1 flex items-center gap-1">📞 <?php echo e($rem['mobile']); ?></p>
                                <p class="text-xs text-indigo-600 mt-1 font-bold bg-indigo-50 inline-block px-2 py-1 rounded">
                                    রেজিঃ <?php echo !empty($rem['reg_date']) ? date('d M, Y', strtotime($rem['reg_date'])) : 'জানা নেই'; ?>
                                </p>
                                
                                <div class="mt-3 text-xs text-slate-600 p-3 bg-white rounded-xl border border-slate-100">
                                    <span class="font-bold text-slate-400 block mb-1">আগের নোট:</span> 
                                    <?php echo e($rem['call_note']); ?>
                                </div>
                                
                                <div class="mt-4 grid grid-cols-3 gap-2">
                                    <a href="index.php?search_query=<?php echo urlencode($rem['card_number']); ?>" class="text-center bg-slate-200 text-slate-700 hover:bg-slate-300 py-2 rounded-lg text-xs font-bold transition">বিস্তারিত</a>
                                    <a href="sms:<?php echo e($rem['mobile']); ?>" class="text-center bg-blue-100 text-blue-700 hover:bg-blue-200 py-2 rounded-lg text-xs font-bold transition">SMS</a>
                                    <a href="https://wa.me/<?php echo substr($rem['mobile'], 0, 2) === '88' ? $rem['mobile'] : '88'.$rem['mobile']; ?>" target="_blank" class="text-center bg-emerald-100 text-emerald-700 hover:bg-emerald-200 py-2 rounded-lg text-xs font-bold transition">WhatsApp</a>
                                </div>
                                
                                <button onclick="openModal(<?php echo $rem['member_id']; ?>, '<?php echo e($rem['member_name']); ?>', '<?php echo e($rem['mobile']); ?>')" class="mt-2 w-full bg-indigo-600 text-white hover:bg-indigo-700 py-2.5 rounded-lg text-sm font-bold transition shadow-md shadow-indigo-200">আবার কল করুন / আপডেট</button>
                            </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="text-center py-8">
                                <div class="text-4xl mb-2">🎉</div>
                                <p class="text-slate-500 text-sm font-bold">আজকের জন্য কোনো রিমাইন্ডার নেই!</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </aside>
        </div>
    </main>

    <!-- Call Log Modal -->
    <div id="callModal" class="fixed inset-0 z-[70] hidden items-center justify-center bg-slate-950/60 backdrop-blur-sm p-4">
        <div class="w-full max-w-lg bg-white rounded-3xl shadow-2xl overflow-hidden relative">
            <div class="p-6 border-b border-slate-100 flex justify-between items-center bg-indigo-50">
                <div>
                    <h3 class="text-xl font-extrabold text-indigo-900">কল আপডেট</h3>
                    <p id="modalPatientName" class="text-sm font-bold text-indigo-600 mt-1">Name</p>
                </div>
                <button onclick="closeModal()" class="text-slate-400 hover:text-slate-600 bg-white p-2 rounded-full shadow-sm">&times; বন্ধ করুন</button>
            </div>
            
            <form action="save_call_log.php" method="POST" class="p-6 space-y-4">
                <input type="hidden" id="modalMemberId" name="member_id" value="">
                
                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">কলের স্ট্যাটাস <span class="text-red-500">*</span></label>
                    <select name="call_status" required class="w-full rounded-xl border-slate-200 bg-slate-50 px-4 py-3 outline-none focus:ring-2 focus:ring-indigo-500 font-semibold text-slate-700">
                        <option value="Answered">✅ কথা হয়েছে</option>
                        <option value="No Answer">📵 কল ধরেনি / রিং হয়েছে</option>
                        <option value="Switched Off">📴 নম্বর বন্ধ</option>
                        <option value="Call Later">📅 পরে কল করতে বলেছে</option>
                        <option value="Wrong Number">❌ ভুল নম্বর</option>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">নোট (রোগী কী বললো?)</label>
                    <textarea name="call_note" rows="3" placeholder="রোগীর বর্তমান অবস্থা বা কী কথা হলো তা সংক্ষেপে লিখুন..." class="w-full rounded-xl border-slate-200 bg-slate-50 px-4 py-3 outline-none focus:ring-2 focus:ring-indigo-500"></textarea>
                </div>

                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">পরবর্তী কলের ডেট (যদি আবার কল করতে হয়)</label>
                    <input type="date" name="next_followup_date" class="w-full rounded-xl border-slate-200 bg-slate-50 px-4 py-3 outline-none focus:ring-2 focus:ring-indigo-500 text-slate-700 font-semibold">
                </div>

                <div class="pt-4">
                    <button type="submit" class="w-full bg-slate-900 text-white font-extrabold text-lg py-3.5 rounded-xl hover:bg-slate-800 transition shadow-lg active:scale-[0.98]">সেভ করুন</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function openModal(id, name, mobile) {
            document.getElementById('modalMemberId').value = id;
            document.getElementById('modalPatientName').innerText = name + ' (' + mobile + ')';
            document.getElementById('callModal').classList.remove('hidden');
            document.getElementById('callModal').classList.add('flex');
        }
        function closeModal() {
            document.getElementById('callModal').classList.add('hidden');
            document.getElementById('callModal').classList.remove('flex');
        }
        
        // Modal close on clicking outside
        document.getElementById('callModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeModal();
            }
        });
    </script>
</body>
</html>