<?php include 'db_connect.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Patient Portal | Aastha Padghan Hospital</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap" rel="stylesheet">
    <style>html { scroll-behavior: smooth; } body { font-family: 'Poppins', sans-serif; }</style>
</head>
<body class="bg-gray-50 text-gray-800 flex flex-col min-h-screen">

    <?php include 'includes/header.php'; ?>

    <div class="bg-teal-800 text-white py-12 text-center relative overflow-hidden">
        <div class="relative z-10">
            <h1 class="text-3xl md:text-4xl font-bold">Patient Portal</h1>
            <p class="text-teal-200 mt-2">Secure Access to Medical Records</p>
        </div>
    </div>

    <div class="container mx-auto px-4 py-10 flex-grow">
        
        <div class="max-w-xl mx-auto bg-white shadow-xl rounded-xl p-8 mb-12 -mt-20 relative z-20 border-t-4 border-teal-500">
            <label class="block text-gray-700 font-bold mb-2 uppercase text-xs tracking-wider">Enter Registered Phone Number</label>
            <form method="POST" class="flex gap-3">
                <input type="tel" name="phone" placeholder="Ex: 9922346009" required 
                       class="flex-grow p-3 border border-gray-300 rounded text-lg focus:ring-2 focus:ring-teal-500 outline-none"
                       value="<?php echo isset($_POST['phone']) ? htmlspecialchars($_POST['phone']) : ''; ?>">
                <button type="submit" name="check_access" class="bg-teal-600 text-white px-8 py-3 rounded font-bold hover:bg-teal-700 transition shadow-lg">Login</button>
            </form>
        </div>

        <?php
        // --- GATEKEEPER LOGIC ---
        if (isset($_POST['check_access']) || isset($_POST['request_access'])) {
            
            $phone = $conn->real_escape_string($_POST['phone']);
            
            // Handle New Request
            if(isset($_POST['request_access'])) {
                $conn->query("INSERT IGNORE INTO portal_access (phone, status) VALUES ('$phone', 'Pending')");
                echo "<div class='max-w-2xl mx-auto bg-yellow-100 border-l-4 border-yellow-500 text-yellow-700 p-4 mb-8 rounded shadow'>
                        <p class='font-bold'>Request Sent!</p>
                        <p>Please wait for the Doctor to approve your access. Try again in some time.</p>
                      </div>";
            }

            // Check Permission
            $perm_sql = "SELECT status FROM portal_access WHERE phone = '$phone'";
            $perm_res = $conn->query($perm_sql);
            $permission = $perm_res->fetch_assoc();

            if ($permission && $permission['status'] == 'Approved') {
                // --- ACCESS GRANTED: SHOW DASHBOARD ---
                
                $appt_res = $conn->query("SELECT * FROM appointments WHERE phone = '$phone' ORDER BY id DESC LIMIT 3");
                $visit_res = $conn->query("SELECT * FROM patient_entries WHERE phone = '$phone' ORDER BY id DESC LIMIT 5");
                $lab_res = $conn->query("SELECT * FROM lab_reports WHERE patient_phone = '$phone' ORDER BY id DESC");
                ?>

                <div class="grid md:grid-cols-2 gap-8 max-w-6xl mx-auto animate-[fadeIn_0.5s_ease-in]">
                    <div class="space-y-8">
                        <div class="bg-white rounded-lg shadow p-6">
                            <h2 class="text-xl font-bold text-gray-800 mb-4 border-b pb-2 flex items-center gap-2">📅 Appointment Status</h2>
                            <?php if ($appt_res->num_rows > 0) {
                                while ($row = $appt_res->fetch_assoc()) {
                                    echo '<div class="flex justify-between items-center py-3 border-b last:border-0">
                                            <div><p class="font-bold">'.$row['doctor'].'</p><p class="text-xs text-gray-500">'.$row['preferred_date'].'</p></div>
                                            <span class="px-3 py-1 rounded-full text-xs font-bold bg-green-100 text-green-700">'.$row['status'].'</span>
                                          </div>';
                                }
                            } else { echo '<p class="text-gray-400 text-sm">No records.</p>'; } ?>
                        </div>

                        <div class="bg-white rounded-lg shadow p-6 border-l-4 border-blue-500">
                            <h2 class="text-xl font-bold text-gray-800 mb-4 border-b pb-2 flex items-center gap-2">👨‍⚕️ Consultations</h2>
                            <?php if ($visit_res->num_rows > 0) {
                                while ($row = $visit_res->fetch_assoc()) {
                                    echo '<div class="mb-4 pb-4 border-b last:border-0">
                                            <p class="font-bold">'.$row['doctor'].' <span class="text-xs text-gray-500">('.$row['visit_date'].')</span></p>
                                            <div class="flex gap-3 mt-2">';
                                    if($row['pdf_file']) echo '<a href="assets/receipts/'.$row['pdf_file'].'" target="_blank" class="bg-gray-100 text-gray-700 px-3 py-1 rounded text-xs font-bold border">Receipt</a>';
                                    if($row['rx_pdf']) echo '<a href="assets/receipts/'.$row['rx_pdf'].'" target="_blank" class="bg-blue-600 text-white px-3 py-1 rounded text-xs font-bold shadow">Prescription</a>';
                                    else echo '<span class="text-xs text-gray-400 py-1">Rx Pending</span>';
                                    echo '</div></div>';
                                }
                            } else { echo '<p class="text-gray-400 text-sm">No records.</p>'; } ?>
                        </div>
                    </div>

                    <div>
                        <div class="bg-white rounded-lg shadow p-6 border-l-4 border-purple-500 h-full">
                            <h2 class="text-xl font-bold text-gray-800 mb-4 border-b pb-2 flex items-center gap-2">🔬 Lab Reports</h2>
                            <?php if ($lab_res->num_rows > 0) {
                                while ($row = $lab_res->fetch_assoc()) {
                                    echo '<div class="flex justify-between items-center py-4 border-b last:border-0 px-2 rounded">
                                            <div><p class="font-bold text-gray-800">'.$row['report_name'].'</p><p class="text-xs text-gray-500">'.$row['uploaded_at'].'</p></div>';
                                    if($row['status'] == 'Approved') {
                                        echo '<a href="assets/reports/'.$row['file_path'].'" target="_blank" class="bg-purple-600 text-white px-4 py-2 rounded text-sm font-bold hover:bg-purple-700 shadow">Download</a>';
                                    } else {
                                        echo '<div class="bg-orange-100 text-orange-700 px-3 py-1 rounded text-xs font-bold">In Review</div>';
                                    }
                                    echo '</div>';
                                }
                            } else { echo '<div class="text-center py-12 opacity-50"><span class="text-5xl">📂</span><p class="text-gray-500 text-sm mt-3">No lab reports.</p></div>'; } ?>
                        </div>
                    </div>
                </div>

            <?php 
            } elseif ($permission && $permission['status'] == 'Pending') {
                // --- CASE: PENDING ---
                echo "<div class='max-w-lg mx-auto bg-orange-50 border border-orange-200 rounded-lg p-8 text-center shadow-lg'>
                        <div class='text-5xl mb-4'>⏳</div>
                        <h2 class='text-2xl font-bold text-orange-800 mb-2'>Access Pending</h2>
                        <p class='text-gray-600'>Your request to view medical records is awaiting Doctor's approval.</p>
                        <p class='text-sm text-gray-500 mt-4'>Please check back later.</p>
                      </div>";
            } else {
                // --- CASE: NO PERMISSION (SHOW REQUEST BUTTON) ---
                echo "<div class='max-w-lg mx-auto bg-white border-t-4 border-red-500 rounded-lg p-8 text-center shadow-2xl'>
                        <div class='text-5xl mb-4'>🔒</div>
                        <h2 class='text-2xl font-bold text-gray-800 mb-2'>Secure Access Required</h2>
                        <p class='text-gray-600 mb-6'>To protect patient privacy, you must request permission to view these records.</p>
                        
                        <form method='POST'>
                            <input type='hidden' name='phone' value='$phone'>
                            <button type='submit' name='request_access' class='bg-red-600 text-white px-8 py-3 rounded-full font-bold hover:bg-red-700 transition shadow-lg transform hover:scale-105'>
                                Request Access Now
                            </button>
                        </form>
                      </div>";
            }
        }
        ?>
    </div>

    <?php include 'includes/footer.php'; ?>

</body>
</html>