<?php
// doctor.php - Complete Doctor Panel with Fixed Login
session_start();
require_once 'config.php';

// ============================================
// DOCTOR LOGIN HANDLER - FIXED
// ============================================
if (isset($_POST['login_action'])) {
    $phone = trim($_POST['phone']);
    $password = $_POST['password'];
    
    // Query doctor
    $result = $conn->query("SELECT * FROM doctors WHERE phone = '$phone' AND is_active = 1");
    
    if ($result && $result->num_rows > 0) {
        $doctor = $result->fetch_assoc();
        
        // Verify password (supports both hashed and plain)
        if (password_verify($password, $doctor['password']) || $doctor['password'] == $password) {
            $_SESSION['doctor_id'] = $doctor['id'];
            $_SESSION['doctor_name'] = $doctor['name'];
            $_SESSION['doctor_phone'] = $doctor['phone'];
            header('Location: doctor.php');
            exit;
        }
    }
    
    // Redirect back with error
    header('Location: doctor.php?error=1');
    exit;
}

// Logout handler
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: doctor.php');
    exit;
}

// Check if doctor is logged in
$is_logged_in = isset($_SESSION['doctor_id']);

// If not logged in and not trying to login, show login form
if (!$is_logged_in && !isset($_POST['login_action'])) {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Doctor Login | <?=$brand['name']?></title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
        <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
        <style>
            body{background:linear-gradient(135deg,#1b4332,#2d6a4f,#52b788);min-height:100vh;display:flex;align-items:center;justify-content:center;font-family:sans-serif}
            .login-card{background:#fff;border-radius:25px;padding:40px;box-shadow:0 20px 60px rgba(0,0,0,.3);max-width:450px;width:100%;animation:fadeInUp 0.6s ease}
            @keyframes fadeInUp{from{opacity:0;transform:translateY(30px)}to{opacity:1;transform:translateY(0)}}
            .login-icon{font-size:4rem;color:#2d6a4f;margin-bottom:20px}
            .btn-login{background:#2d6a4f;color:#fff;border-radius:30px;padding:12px;font-weight:600;width:100%;border:none}
            .btn-login:hover{background:#1b4332;transform:translateY(-2px)}
            .input-group-text{background:#f8f9fa}
        </style>
    </head>
    <body>
        <div class="login-card">
            <div class="text-center">
                <div class="login-icon">
                    <i class="fas fa-user-md"></i>
                </div>
                <h3 class="mb-2">Doctor Login</h3>
                <p class="text-muted mb-4">Login with your registered phone number</p>
            </div>
            
            <?php if(isset($_GET['error'])): ?>
                <div class="alert alert-danger text-center">
                    <i class="fas fa-exclamation-circle"></i> Invalid phone number or password!
                </div>
            <?php endif; ?>
            
            <form method="POST" action="">
                <div class="mb-3">
                    <div class="input-group">
                        <span class="input-group-text"><i class="fas fa-phone"></i></span>
                        <input type="tel" name="phone" class="form-control" placeholder="Phone Number" required autofocus>
                    </div>
                </div>
                <div class="mb-4">
                    <div class="input-group">
                        <span class="input-group-text"><i class="fas fa-lock"></i></span>
                        <input type="password" name="password" class="form-control" placeholder="Password" required>
                    </div>
                </div>
                <button type="submit" name="login_action" class="btn btn-login">
                    <i class="fas fa-sign-in-alt"></i> Login
                </button>
            </form>
            <hr class="my-4">
            <div class="text-center">
                <p class="text-muted small mb-0">
                    <i class="fas fa-shield-alt"></i> Secure access for registered doctors only
                </p>
                <p class="text-muted small mt-2">
                    <i class="fas fa-phone"></i> Contact admin if you don't have credentials
                </p>
            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    </body>
    </html>
    <?php
    exit;
}

// ============================================
// DOCTOR DASHBOARD (Logged In)
// ============================================
$doctor_id = (int)$_SESSION['doctor_id'];
$doctor = $conn->query("SELECT * FROM doctors WHERE id = $doctor_id")->fetch_assoc();

if (!$doctor) {
    session_destroy();
    header('Location: doctor.php?error=1');
    exit;
}

// Get today's appointments
$today = date('Y-m-d');
$today_appointments = $conn->query("SELECT a.*, p.name as patient_name, p.mobile, p.age, p.address 
                                     FROM opd_appointments a 
                                     LEFT JOIN opd_patients p ON a.patient_id = p.id 
                                     WHERE a.doctor_id = $doctor_id AND a.appointment_date = '$today' 
                                     ORDER BY a.serial_no ASC");

// Get upcoming appointments
$upcoming_appointments = $conn->query("SELECT a.*, p.name as patient_name, p.mobile, p.age, p.address 
                                        FROM opd_appointments a 
                                        LEFT JOIN opd_patients p ON a.patient_id = p.id 
                                        WHERE a.doctor_id = $doctor_id AND a.appointment_date > '$today' AND a.status != 'cancelled'
                                        ORDER BY a.appointment_date ASC, a.serial_no ASC LIMIT 30");

// Get past appointments
$past_appointments = $conn->query("SELECT a.*, p.name as patient_name, p.mobile, p.age, p.address 
                                   FROM opd_appointments a 
                                   LEFT JOIN opd_patients p ON a.patient_id = p.id 
                                   WHERE a.doctor_id = $doctor_id AND a.appointment_date < '$today' 
                                   ORDER BY a.appointment_date DESC LIMIT 40");

// Get prescriptions
$prescriptions = $conn->query("SELECT pr.*, p.name as patient_name, a.appointment_date 
                               FROM opd_prescriptions pr 
                               LEFT JOIN opd_appointments a ON pr.appointment_id = a.id 
                               LEFT JOIN opd_patients p ON pr.patient_id = p.id 
                               WHERE pr.doctor_id = $doctor_id 
                               ORDER BY pr.created_at DESC LIMIT 40");

// Get all patients
$all_patients = $conn->query("SELECT id, name, mobile, age, address FROM opd_patients ORDER BY id DESC LIMIT 100");

// Get statistics
$total_appointments = $conn->query("SELECT COUNT(*) as total FROM opd_appointments WHERE doctor_id = $doctor_id")->fetch_assoc()['total'];
$completed_appointments = $conn->query("SELECT COUNT(*) as total FROM opd_appointments WHERE doctor_id = $doctor_id AND status = 'completed'")->fetch_assoc()['total'];
$total_prescriptions = $conn->query("SELECT COUNT(*) as total FROM opd_prescriptions WHERE doctor_id = $doctor_id")->fetch_assoc()['total'];

// Handle appointment status update
if (isset($_POST['update_status'])) {
    $appointment_id = (int)$_POST['appointment_id'];
    $status = $_POST['status'];
    $conn->query("UPDATE opd_appointments SET status = '$status' WHERE id = $appointment_id AND doctor_id = $doctor_id");
    $_SESSION['doc_msg'] = "✅ Appointment status updated!";
    header('Location: doctor.php?tab=' . ($_GET['tab'] ?? 'today'));
    exit;
}

// Handle add prescription
if (isset($_POST['add_prescription'])) {
    $appointment_id = (int)$_POST['appointment_id'];
    $patient_id = (int)$_POST['patient_id'];
    $prescription_text = $conn->real_escape_string($_POST['prescription_text']);
    $advice = $conn->real_escape_string($_POST['advice']);
    $next_visit = !empty($_POST['next_visit']) ? "'{$_POST['next_visit']}'" : "NULL";
    
    $conn->query("INSERT INTO opd_prescriptions (appointment_id, patient_id, doctor_id, prescription_text, advice, next_visit) 
                  VALUES ($appointment_id, $patient_id, $doctor_id, '$prescription_text', '$advice', $next_visit)");
    
    $conn->query("UPDATE opd_appointments SET status = 'completed' WHERE id = $appointment_id");
    
    $_SESSION['doc_msg'] = "✅ Prescription added successfully!";
    header('Location: doctor.php?tab=today');
    exit;
}

// Handle profile update
if (isset($_POST['update_profile'])) {
    $name = $conn->real_escape_string($_POST['name']);
    $degree = $conn->real_escape_string($_POST['degree']);
    $specialization = $conn->real_escape_string($_POST['specialization']);
    $experience = $conn->real_escape_string($_POST['experience']);
    $phone = $conn->real_escape_string($_POST['phone']);
    $whatsapp = $conn->real_escape_string($_POST['whatsapp']);
    $chamber = $conn->real_escape_string($_POST['chamber']);
    $bio = $conn->real_escape_string($_POST['bio']);
    
    $photo = $doctor['photo'];
    if (isset($_FILES['photo']) && $_FILES['photo']['error'] == 0) {
        $upload = uploadImage($_FILES['photo'], 'uploads/doctors/');
        if ($upload) $photo = $upload;
    }
    
    // Update password if provided
    if (!empty($_POST['password'])) {
        $new_password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $conn->query("UPDATE doctors SET password = '$new_password' WHERE id = $doctor_id");
    }
    
    $conn->query("UPDATE doctors SET 
                  name = '$name', degree = '$degree', specialization = '$specialization',
                  experience = '$experience', phone = '$phone', whatsapp = '$whatsapp',
                  chamber = '$chamber', bio = '$bio', photo = '$photo'
                  WHERE id = $doctor_id");
    
    $_SESSION['doc_msg'] = "✅ Profile updated successfully!";
    header('Location: doctor.php?tab=profile');
    exit;
}

// Handle new patient
if (isset($_POST['add_patient'])) {
    $name = $conn->real_escape_string($_POST['patient_name']);
    $mobile = $conn->real_escape_string($_POST['patient_mobile']);
    $age = (int)$_POST['patient_age'];
    $address = $conn->real_escape_string($_POST['patient_address']);
    
    $conn->query("INSERT INTO opd_patients (name, mobile, age, address, created_at) 
                  VALUES ('$name', '$mobile', $age, '$address', NOW())");
    
    $_SESSION['doc_msg'] = "✅ New patient added!";
    header('Location: doctor.php?tab=appointments');
    exit;
}

// Handle book appointment
if (isset($_POST['book_appointment'])) {
    $patient_id = (int)$_POST['patient_id'];
    $appointment_date = $_POST['appointment_date'];
    $serial_no = (int)$_POST['serial_no'];
    
    $check = $conn->query("SELECT id FROM opd_appointments WHERE doctor_id = $doctor_id AND appointment_date = '$appointment_date' AND serial_no = $serial_no");
    if ($check->num_rows > 0) {
        $_SESSION['doc_msg'] = "❌ Serial #$serial_no is already booked!";
    } else {
        $conn->query("INSERT INTO opd_appointments (patient_id, doctor_id, appointment_date, serial_no, status, payment_status) 
                      VALUES ($patient_id, $doctor_id, '$appointment_date', $serial_no, 'confirmed', 'unpaid')");
        $_SESSION['doc_msg'] = "✅ Appointment booked successfully!";
    }
    header('Location: doctor.php?tab=appointments');
    exit;
}

$tab = $_GET['tab'] ?? 'dashboard';
$doc_msg = $_SESSION['doc_msg'] ?? '';
unset($_SESSION['doc_msg']);
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Doctor Panel | <?=$brand['name']?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        :root{--p:#2d6a4f;--pl:#52b788;--pd:#1b4332}
        *{font-family:'Hind Siliguri',sans-serif}
        body{background:#f0f2f5;overflow-x:hidden}
        
        .sidebar{background:linear-gradient(180deg,#1b4332,#2d6a4f);min-height:100vh;color:#fff;position:fixed;width:270px;z-index:1000;overflow-y:auto}
        .sidebar .brand{padding:20px;text-align:center;border-bottom:1px solid rgba(255,255,255,.1)}
        .sidebar .user-info{padding:20px;text-align:center;border-bottom:1px solid rgba(255,255,255,.1)}
        .sidebar .user-avatar{width:80px;height:80px;border-radius:50%;margin:0 auto 10px;border:3px solid var(--pl);object-fit:cover}
        .sidebar .user-name{font-weight:700}
        .sidebar a{color:rgba(255,255,255,.85);text-decoration:none;padding:12px 20px;display:block;margin:2px 10px;border-radius:10px;transition:.3s}
        .sidebar a:hover,.sidebar a.active{background:rgba(255,255,255,.15);color:#fff}
        .sidebar a i{width:22px;margin-right:10px}
        .main-content{margin-left:270px;padding:25px;min-height:100vh}
        .stat-card{background:#fff;border-radius:15px;padding:20px;box-shadow:0 2px 10px rgba(0,0,0,.05);transition:all .3s}
        .stat-card:hover{transform:translateY(-5px)}
        .stat-number{font-size:2rem;font-weight:800;color:var(--p)}
        .appointment-card{background:#fff;border-radius:12px;padding:15px;margin-bottom:15px;border-left:4px solid var(--p)}
        .status-badge{padding:4px 12px;border-radius:20px;font-size:.7rem;font-weight:600}
        .status-confirmed{background:#ffc107;color:#333}
        .status-completed{background:#28a745;color:#fff}
        .status-cancelled{background:#dc3545;color:#fff}
        .prescription-text{font-family:monospace;font-size:14px}
        @media(max-width:768px){.sidebar{position:static;width:100%}.main-content{margin-left:0}}
        .animated{animation:fadeInUp .5s ease}
        @keyframes fadeInUp{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}
    </style>
</head>
<body>

<div class="d-flex flex-wrap">
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="brand">
            <h5><i class="fas fa-user-md"></i> <?=$brand['name']?></h5>
            <small>Doctor Panel</small>
        </div>
        <div class="user-info">
            <?php if($doctor['photo']): ?>
                <img src="<?=$doctor['photo']?>" class="user-avatar" alt="Doctor">
            <?php else: ?>
                <div class="user-avatar d-flex align-items-center justify-content-center bg-white text-success mx-auto" style="font-size:2rem;">
                    <i class="fas fa-user-md"></i>
                </div>
            <?php endif; ?>
            <div class="user-name">Dr. <?=htmlspecialchars($doctor['name'])?></div>
            <div class="user-specialty small opacity-75"><?=htmlspecialchars($doctor['specialization'])?></div>
        </div>
        <a href="?tab=dashboard" class="<?=$tab=='dashboard'?'active':''?>"><i class="fas fa-th-large"></i> Dashboard</a>
        <a href="?tab=today" class="<?=$tab=='today'?'active':''?>"><i class="fas fa-calendar-day"></i> Today's Appointments</a>
        <a href="?tab=upcoming" class="<?=$tab=='upcoming'?'active':''?>"><i class="fas fa-calendar-week"></i> Upcoming</a>
        <a href="?tab=past" class="<?=$tab=='past'?'active':''?>"><i class="fas fa-history"></i> Past Appointments</a>
        <a href="?tab=appointments" class="<?=$tab=='appointments'?'active':''?>"><i class="fas fa-calendar-plus"></i> Manage Appointments</a>
        <a href="?tab=prescriptions" class="<?=$tab=='prescriptions'?'active':''?>"><i class="fas fa-prescription"></i> Prescriptions</a>
        <a href="?tab=patients" class="<?=$tab=='patients'?'active':''?>"><i class="fas fa-users"></i> Patients</a>
        <a href="?tab=profile" class="<?=$tab=='profile'?'active':''?>"><i class="fas fa-user-edit"></i> Profile</a>
        <hr style="border-color:rgba(255,255,255,.2)">
        <a href="?logout=1" onclick="return confirm('Logout?')"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <?php if($doc_msg): ?>
            <div class="alert alert-success alert-dismissible fade show animated"><?=$doc_msg?><button class="btn-close" data-bs-dismiss="alert"></button></div>
        <?php endif; ?>

        <!-- DASHBOARD TAB -->
        <?php if($tab=='dashboard'): ?>
        <div class="animated">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h4><i class="fas fa-chart-line"></i> Welcome, Dr. <?=htmlspecialchars($doctor['name'])?></h4>
                <span class="text-muted"><?=date('l, d M Y')?></span>
            </div>
            <a href="case/doctor_cases.php"><i class="fas fa-folder-medical"></i> Case Management</a>
            <div class="row g-3 mb-4">
                <div class="col-md-3 col-6">
                    <div class="stat-card text-center">
                        <div class="stat-number"><?=$total_appointments?></div>
                        <div class="stat-label">Total Appointments</div>
                    </div>
                </div>
                <div class="col-md-3 col-6">
                    <div class="stat-card text-center">
                        <div class="stat-number"><?=$today_appointments->num_rows?></div>
                        <div class="stat-label">Today's Appointments</div>
                    </div>
                </div>
                <div class="col-md-3 col-6">
                    <div class="stat-card text-center">
                        <div class="stat-number"><?=$completed_appointments?></div>
                        <div class="stat-label">Completed</div>
                    </div>
                </div>
                
                <div class="col-md-3 col-6">
                    <div class="stat-card text-center">
                        <div class="stat-number"><?=$total_prescriptions?></div>
                        <div class="stat-label">Prescriptions</div>
                    </div>
                </div>
            </div>
            
            <?php if($today_appointments->num_rows > 0): ?>
            <div class="card">
                <div class="card-header bg-white fw-bold">📋 Today's Schedule</div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead class="table-light"><tr><th>Serial</th><th>Patient</th><th>Status</th><th>Action</th></tr></thead>
                            <tbody>
                                <?php while($apt = $today_appointments->fetch_assoc()): ?>
                                <tr>
                                    <td><span class="badge bg-primary">#<?=$apt['serial_no']?></span></td>
                                    <td><strong><?=htmlspecialchars($apt['patient_name'])?></strong><br><small><?=$apt['mobile']?></small></td>
                                    <td><span class="status-badge status-<?=$apt['status']?>"><?=ucfirst($apt['status'])?></span></td>
                                    <td><button class="btn btn-sm btn-primary" onclick="consultPatient(<?=$apt['patient_id']?>, <?=$apt['id']?>)">Consult</button></td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php else: ?>
            <div class="alert alert-info">No appointments scheduled for today. Enjoy your day! 🎉</div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <!-- TODAY'S APPOINTMENTS TAB -->
        <?php if($tab=='today'): ?>
        <div class="animated">
            <h4 class="mb-4"><i class="fas fa-calendar-day"></i> Today's Appointments (<?=$today_appointments->num_rows?>)</h4>
            <?php if($today_appointments->num_rows > 0): ?>
                <?php $today_appointments->data_seek(0); while($apt = $today_appointments->fetch_assoc()): ?>
                <div class="appointment-card">
                    <div class="row align-items-center">
                        <div class="col-md-2"><span class="badge bg-primary" style="font-size:1rem">#<?=$apt['serial_no']?></span></div>
                        <div class="col-md-4"><strong><?=htmlspecialchars($apt['patient_name'])?></strong><br><small><?=$apt['mobile']?></small></div>
                        <div class="col-md-2"><span class="status-badge status-<?=$apt['status']?>"><?=ucfirst($apt['status'])?></span></div>
                        <div class="col-md-4 text-end"><button class="btn btn-primary" onclick="consultPatient(<?=$apt['patient_id']?>, <?=$apt['id']?>)"><i class="fas fa-stethoscope"></i> Start Consultation</button></div>
                    </div>
                </div>
                <?php endwhile; ?>
            <?php else: ?>
                <div class="alert alert-info">No appointments scheduled for today.</div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <!-- UPCOMING, PAST, APPOINTMENTS, PRESCRIPTIONS, PATIENTS, PROFILE TABS -->
        <!-- Same as previous working version - keeping it concise -->

        <?php if($tab=='upcoming'): ?>
        <div class="animated">
            <h4 class="mb-4"><i class="fas fa-calendar-week"></i> Upcoming Appointments</h4>
            <?php while($apt = $upcoming_appointments->fetch_assoc()): ?>
            <div class="appointment-card">
                <div class="row align-items-center">
                    <div class="col-md-3"><strong><?=date('d M Y', strtotime($apt['appointment_date']))?></strong><br><small>#<?=$apt['serial_no']?></small></div>
                    <div class="col-md-4"><strong><?=htmlspecialchars($apt['patient_name'])?></strong><br><small><?=$apt['mobile']?></small></div>
                    <div class="col-md-2"><span class="status-badge status-<?=$apt['status']?>"><?=ucfirst($apt['status'])?></span></div>
                    <div class="col-md-3 text-end">
                        <form method="POST" class="d-inline">
                            <input type="hidden" name="appointment_id" value="<?=$apt['id']?>">
                            <input type="hidden" name="status" value="cancelled">
                            <button type="submit" name="update_status" class="btn btn-sm btn-outline-danger" onclick="return confirm('Cancel?')">Cancel</button>
                        </form>
                    </div>
                </div>
            </div>
            <?php endwhile; ?>
        </div>
        <?php endif; ?>

        <?php if($tab=='past'): ?>
        <div class="animated">
            <h4 class="mb-4"><i class="fas fa-history"></i> Past Appointments</h4>
            <?php while($apt = $past_appointments->fetch_assoc()): ?>
            <div class="appointment-card">
                <div class="row align-items-center">
                    <div class="col-md-3"><strong><?=date('d M Y', strtotime($apt['appointment_date']))?></strong></div>
                    <div class="col-md-5"><strong><?=htmlspecialchars($apt['patient_name'])?></strong><br><small><?=$apt['mobile']?></small></div>
                    <div class="col-md-2"><span class="status-badge status-<?=$apt['status']?>"><?=ucfirst($apt['status'])?></span></div>
                    <div class="col-md-2 text-end"><button class="btn btn-sm btn-info" onclick="alert('Patient: <?=addslashes($apt['patient_name'])?>\nPhone: <?=$apt['mobile']?>\nAddress: <?=addslashes($apt['address'])?>')">View</button></div>
                </div>
            </div>
            <?php endwhile; ?>
        </div>
        <?php endif; ?>

        <?php if($tab=='appointments'): ?>
        <div class="animated">
            <h4 class="mb-4"><i class="fas fa-calendar-plus"></i> Book New Appointment</h4>
            <div class="card mb-4"><div class="card-body">
                <form method="POST">
                    <div class="row">
                        <div class="col-md-4 mb-2"><label>Patient</label><select name="patient_id" class="form-select" required><option value="">-- Select --</option><?php $all_patients->data_seek(0); while($p=$all_patients->fetch_assoc()):?><option value="<?=$p['id']?>"><?=htmlspecialchars($p['name'])?> (<?=$p['mobile']?>)</option><?php endwhile;?></select></div>
                        <div class="col-md-3 mb-2"><label>Date</label><input type="date" name="appointment_date" class="form-control" value="<?=date('Y-m-d',strtotime('+1 day'))?>" required></div>
                        <div class="col-md-2 mb-2"><label>Serial</label><input type="number" name="serial_no" class="form-control" placeholder="1-50" required></div>
                        <div class="col-md-3 mb-2"><label>&nbsp;</label><button type="submit" name="book_appointment" class="btn btn-primary w-100">Book</button></div>
                    </div>
                </form>
            </div></div>
            <h5>Quick Add Patient</h5>
            <div class="card"><div class="card-body">
                <form method="POST"><div class="row"><div class="col-md-3"><input type="text" name="patient_name" class="form-control" placeholder="Name" required></div><div class="col-md-2"><input type="tel" name="patient_mobile" class="form-control" placeholder="Mobile" required></div><div class="col-md-2"><input type="number" name="patient_age" class="form-control" placeholder="Age"></div><div class="col-md-3"><input type="text" name="patient_address" class="form-control" placeholder="Address"></div><div class="col-md-2"><button type="submit" name="add_patient" class="btn btn-success w-100">+ Add</button></div></div></form>
            </div></div>
        </div>
        <?php endif; ?>

        <?php if($tab=='prescriptions'): ?>
        <div class="animated">
            <h4 class="mb-4"><i class="fas fa-prescription"></i> My Prescriptions</h4>
            <div class="table-responsive"><table class="table table-hover"><thead class="table-light"><tr><th>Date</th><th>Patient</th><th>Prescription</th><th>Next Visit</th></tr></thead><tbody>
            <?php while($pr=$prescriptions->fetch_assoc()):?><tr><td><?=date('d M Y',strtotime($pr['created_at']))?></td><td><strong><?=htmlspecialchars($pr['patient_name'])?></strong></td><td><small><?=substr($pr['prescription_text'],0,50)?>...</small></td><td><?=$pr['next_visit']?date('d M Y',strtotime($pr['next_visit'])):'-'?></td></tr><?php endwhile;?>
            </tbody></table></div>
        </div>
        <?php endif; ?>

        <?php if($tab=='patients'): ?>
        <div class="animated">
            <h4 class="mb-4"><i class="fas fa-users"></i> All Patients</h4>
            <input type="text" id="searchPatient" class="form-control mb-3" placeholder="Search by name or phone...">
            <div class="table-responsive"><table class="table table-hover" id="patientsTable"><thead class="table-light"><tr><th>Name</th><th>Mobile</th><th>Age</th><th>Action</th></tr></thead><tbody>
            <?php $all_patients->data_seek(0); while($p=$all_patients->fetch_assoc()):?><tr><td><strong><?=htmlspecialchars($p['name'])?></strong></td><td><?=$p['mobile']?></td><td><?=$p['age']?:'-'?></td><td><button class="btn btn-sm btn-primary" onclick="bookForPatient(<?=$p['id']?>)">Book Appointment</button></td></tr><?php endwhile;?>
            </tbody></table></div>
        </div>
        <?php endif; ?>

        <?php if($tab=='profile'): ?>
        <div class="animated">
            <h4 class="mb-4"><i class="fas fa-user-edit"></i> My Profile</h4>
            <div class="card"><div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <div class="row">
                        <div class="col-md-3 text-center">
                            <?php if($doctor['photo']):?><img src="<?=$doctor['photo']?>" class="rounded-circle mb-2" style="width:100px;height:100px;object-fit:cover"><?php else:?><div class="rounded-circle bg-light d-inline-flex align-items-center justify-content-center mb-2" style="width:100px;height:100px;font-size:2rem"><i class="fas fa-user-md"></i></div><?php endif;?>
                            <input type="file" name="photo" class="form-control" accept="image/*">
                        </div>
                        <div class="col-md-9">
                            <div class="row">
                                <div class="col-md-6 mb-2"><label>Name</label><input type="text" name="name" class="form-control" value="<?=htmlspecialchars($doctor['name'])?>" required></div>
                                <div class="col-md-6 mb-2"><label>Degree</label><input type="text" name="degree" class="form-control" value="<?=htmlspecialchars($doctor['degree'])?>"></div>
                                <div class="col-md-6 mb-2"><label>Specialization</label><input type="text" name="specialization" class="form-control" value="<?=htmlspecialchars($doctor['specialization'])?>"></div>
                                <div class="col-md-6 mb-2"><label>Experience</label><input type="text" name="experience" class="form-control" value="<?=htmlspecialchars($doctor['experience'])?>"></div>
                                <div class="col-md-6 mb-2"><label>Phone</label><input type="tel" name="phone" class="form-control" value="<?=$doctor['phone']?>"></div>
                                <div class="col-md-6 mb-2"><label>WhatsApp</label><input type="text" name="whatsapp" class="form-control" value="<?=$doctor['whatsapp']?>"></div>
                                <div class="col-12 mb-2"><label>Chamber</label><input type="text" name="chamber" class="form-control" value="<?=htmlspecialchars($doctor['chamber'])?>"></div>
                                <div class="col-12 mb-2"><label>Bio</label><textarea name="bio" class="form-control" rows="2"><?=htmlspecialchars($doctor['bio'])?></textarea></div>
                                <div class="col-12 mb-2"><label>New Password (leave empty to keep current)</label><input type="password" name="password" class="form-control" placeholder="Enter new password"></div>
                            </div>
                        </div>
                    </div>
                    <button type="submit" name="update_profile" class="btn btn-primary mt-3">Update Profile</button>
                </form>
            </div></div>
        </div>
        <?php endif; ?>

    </div>
</div>

<!-- Consultation Modal -->
<div class="modal fade" id="consultModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><i class="fas fa-stethoscope"></i> Patient Consultation</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="consultModalBody">Loading...</div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
function consultPatient(patientId, appointmentId) {
    fetch('ajax_get_patient.php?patient_id=' + patientId + '&appointment_id=' + appointmentId)
        .then(response => response.json())
        .then(data => {
            let html = `
                <div class="row mb-3">
                    <div class="col-md-6"><div class="border p-2 rounded bg-light"><strong>Patient:</strong> ${data.patient.name}<br><strong>Mobile:</strong> ${data.patient.mobile}<br><strong>Age:</strong> ${data.patient.age || 'N/A'}</div></div>
                    <div class="col-md-6"><div class="border p-2 rounded bg-light"><strong>Serial #${data.appointment.serial_no}</strong><br><strong>Date:</strong> ${data.appointment.appointment_date}</div></div>
                </div>
                <form method="POST">
                    <input type="hidden" name="appointment_id" value="${appointmentId}">
                    <input type="hidden" name="patient_id" value="${patientId}">
                    <div class="mb-2"><label>Prescription</label><textarea name="prescription_text" class="form-control prescription-text" rows="5" placeholder="Medicine with dosage..."></textarea></div>
                    <div class="mb-2"><label>Advice</label><textarea name="advice" class="form-control" rows="2"></textarea></div>
                    <div class="mb-2"><label>Next Visit</label><input type="date" name="next_visit" class="form-control"></div>
                    <button type="submit" name="add_prescription" class="btn btn-primary w-100">Save Prescription</button>
                </form>
            `;
            document.getElementById('consultModalBody').innerHTML = html;
            new bootstrap.Modal(document.getElementById('consultModal')).show();
        });
}

function bookForPatient(patientId) {
    window.location.href = '?tab=appointments';
    setTimeout(() => {
        document.querySelector('select[name="patient_id"]').value = patientId;
    }, 500);
}

document.getElementById('searchPatient')?.addEventListener('keyup', function() {
    let search = this.value.toLowerCase();
    document.querySelectorAll('#patientsTable tbody tr').forEach(row => {
        row.style.display = row.innerText.toLowerCase().includes(search) ? '' : 'none';
    });
});
</script>
</body>
</html>