<?php
// Enable Error Reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
if (!isset($_SESSION['doctor_logged_in'])) { header("Location: login.php"); exit(); }
include '../db_connect.php';
date_default_timezone_set('Asia/Kolkata');

// Get Dynamic Doctor Details from Session
$current_doctor = $_SESSION['doctor_name'];
$theme = $_SESSION['theme_color']; // 'teal' or 'pink'
$today = date('Y-m-d');

// Safe Database Fetching
function get_count($conn, $sql) {
    $result = $conn->query($sql);
    return ($result) ? ($result->fetch_assoc()['count'] ?? 0) : 0;
}

$wait_count = get_count($conn, "SELECT COUNT(*) as count FROM patient_entries WHERE visit_date = '$today' AND doctor = '$current_doctor' AND status = 'Waiting'");
$done_count = get_count($conn, "SELECT COUNT(*) as count FROM patient_entries WHERE visit_date = '$today' AND doctor = '$current_doctor' AND status = 'Completed'");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title><?php echo $current_doctor; ?>'s Desk</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <meta http-equiv="refresh" content="60"> 
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap" rel="stylesheet">
    <style>body { font-family: 'Poppins', sans-serif; }</style>
</head>
<body class="bg-gray-50 min-h-screen">
    
    <nav class="bg-<?php echo $theme; ?>-700 text-white p-4 shadow-lg flex flex-col md:flex-row justify-between items-center sticky top-0 z-50">
        
        <div class="flex items-center gap-3 mb-3 md:mb-0">
            <div class="w-12 h-12 bg-white rounded-full flex items-center justify-center text-<?php echo $theme; ?>-800 font-bold text-2xl border-2 border-<?php echo $theme; ?>-200">
                <?php echo ($theme == 'pink') ? '👩‍⚕️' : '👨‍⚕️'; ?>
            </div>
            <div>
                <h1 class="text-lg font-bold leading-tight"><?php echo $current_doctor; ?></h1>
                <p class="text-xs text-<?php echo $theme; ?>-200 opacity-90">
                    <?php echo ($theme == 'pink') ? 'Cosmetology & Skin Specialist' : 'General & Laparoscopic Surgeon'; ?>
                </p>
            </div>
        </div>

        <div class="flex flex-wrap gap-2 items-center justify-center">
            <a href="new_rx.php" class="bg-white text-<?php echo $theme; ?>-700 hover:bg-gray-100 px-3 py-2 rounded text-sm font-bold transition shadow flex items-center gap-1">
                📝 Add New Patient
            </a>
            <a href="rx_history.php" class="bg-<?php echo $theme; ?>-800 hover:bg-<?php echo $theme; ?>-900 text-white px-3 py-2 rounded text-sm font-bold transition shadow border border-<?php echo $theme; ?>-600">
                📜 History
            </a>
            <a href="../staff/beds.php" target="_blank" class="bg-orange-500 hover:bg-orange-600 text-white px-3 py-2 rounded text-sm font-bold transition flex items-center gap-1 shadow">
                🛏️ Beds
            </a>
            <a href="approve_reports.php" class="bg-purple-600 hover:bg-purple-700 text-white px-3 py-2 rounded text-sm font-bold transition shadow">
                📂 Reports
            </a>
            <a href="approve_access.php" class="bg-blue-600 hover:bg-blue-700 text-white px-3 py-2 rounded text-sm font-bold transition shadow">
                🔑 Access
            </a>
            <a href="login.php" class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded text-sm font-bold transition shadow">
                Logout
            </a>
        </div>
    </nav>

    <div class="container mx-auto p-6">
        
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
            <div class="bg-white p-4 rounded-lg shadow border-l-4 border-blue-500">
                <p class="text-gray-500 text-xs uppercase font-bold">Waiting Now</p>
                <p class="text-3xl font-bold text-blue-600"><?php echo $wait_count; ?></p>
            </div>
            <div class="bg-white p-4 rounded-lg shadow border-l-4 border-green-500">
                <p class="text-gray-500 text-xs uppercase font-bold">Checked Today</p>
                <p class="text-3xl font-bold text-green-600"><?php echo $done_count; ?></p>
            </div>
            <div class="bg-white p-4 rounded-lg shadow border-l-4 border-gray-400 md:col-span-2">
                <p class="text-gray-500 text-xs uppercase font-bold">Today's Date</p>
                <p class="text-lg font-bold text-gray-700 flex items-center gap-2">
                    📅 <?php echo date('d F Y'); ?> 
                    <span class="text-xs font-normal bg-gray-100 px-2 py-1 rounded text-gray-500">IST</span>
                </p>
            </div>
        </div>

        <h2 class="text-xl font-bold text-gray-700 mb-4 flex items-center gap-2">
            <span>⏳ Patient Queue</span>
            <span class="text-sm font-normal text-<?php echo $theme; ?>-600 bg-<?php echo $theme; ?>-50 border border-<?php echo $theme; ?>-200 px-2 py-1 rounded">Live Updates</span>
        </h2>
        
        <div class="grid md:grid-cols-3 gap-6">
            <?php
            // Fetch ONLY THIS Doctor's Waiting Patients
            $sql = "SELECT * FROM patient_entries WHERE visit_date = '$today' AND doctor = '$current_doctor' AND status = 'Waiting' ORDER BY id ASC";
            $result = $conn->query($sql);

            if ($result && $result->num_rows > 0) {
                while($row = $result->fetch_assoc()) {
                    ?>
                    <div class="bg-white rounded-xl shadow-md hover:shadow-xl transition border-t-4 border-<?php echo $theme; ?>-500 relative overflow-hidden group">
                        <div class="p-6">
                            <div class="flex justify-between items-start mb-4">
                                <div>
                                    <h3 class="text-xl font-bold text-gray-800"><?php echo $row['patient_name']; ?></h3>
                                    <p class="text-gray-500 text-sm">📱 <?php echo $row['phone']; ?></p>
                                </div>
                                <span class="bg-<?php echo $theme; ?>-100 text-<?php echo $theme; ?>-800 text-xs font-bold px-2 py-1 rounded">
                                    Token #<?php echo $row['id']; ?>
                                </span>
                            </div>
                            
                            <div class="mt-4">
                                <a href="consult.php?id=<?php echo $row['id']; ?>" class="flex w-full bg-<?php echo $theme; ?>-600 text-white text-center py-3 rounded-lg font-bold hover:bg-<?php echo $theme; ?>-700 transition shadow justify-center items-center gap-2">
                                    <span>Start Checkup</span>
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3"></path></svg>
                                </a>
                            </div>
                        </div>
                    </div>
                    <?php
                }
            } else {
                echo "
                <div class='col-span-3 flex flex-col items-center justify-center py-12 bg-white rounded-lg border-2 border-dashed border-gray-300'>
                    <div class='text-4xl mb-2'>☕</div>
                    <p class='text-gray-500 font-medium'>No patients waiting in queue.</p>
                    <p class='text-sm text-gray-400'>All clear, $current_doctor!</p>
                </div>";
            }
            ?>
        </div>

        <h2 class="text-lg font-bold text-gray-600 mt-12 mb-4">✅ Completed Consultations (Today)</h2>
        <div class="bg-white rounded-lg shadow overflow-hidden">
            <table class="w-full text-left text-sm">
                <thead class="bg-gray-50 border-b">
                    <tr>
                        <th class="p-4 text-gray-500 font-medium">Patient Name</th>
                        <th class="p-4 text-gray-500 font-medium">Diagnosis</th>
                        <th class="p-4 text-gray-500 font-medium">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $done_sql = "SELECT * FROM patient_entries WHERE visit_date = '$today' AND doctor = '$current_doctor' AND status = 'Completed' ORDER BY id DESC";
                    $done_res = $conn->query($done_sql);
                    
                    if ($done_res && $done_res->num_rows > 0) {
                        while($row = $done_res->fetch_assoc()) {
                            echo "<tr class='border-b hover:bg-gray-50 transition'>";
                            echo "<td class='p-4 font-bold text-gray-800'>{$row['patient_name']}</td>";
                            echo "<td class='p-4 text-gray-600 truncate max-w-xs'>{$row['diagnosis']}</td>";
                            echo "<td class='p-4'>
                                    <a href='../assets/receipts/{$row['rx_pdf']}' target='_blank' class='text-blue-600 font-bold hover:underline flex items-center gap-1'>
                                        <svg class='w-4 h-4' fill='none' stroke='currentColor' viewBox='0 0 24 24'><path stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M15 12a3 3 0 11-6 0 3 3 0 016 0z'></path><path stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z'></path></svg>
                                        View Rx
                                    </a>
                                  </td>";
                            echo "</tr>";
                        }
                    } else {
                        echo "<tr><td colspan='3' class='p-4 text-center text-gray-400'>No completed cases yet.</td></tr>";
                    }
                    ?>
                </tbody>
            </table>
        </div>

    </div>
</body>
</html>