<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (!isset($_SESSION['admin_id'])) { header("Location: login.php"); exit(); }
include '../include/config.php';

$msg = '';
$error = '';

// Handle appointment status update
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['update_status'])) {
        $appointment_id = (int)$_POST['appointment_id'];
        $new_status = $_POST['status'];
        
        // Get patient_id and doctor_name before update
        $appt_info = $conn->query("SELECT a.patient_id, d.name as doctor_name, a.appointment_date, a.appointment_time 
                                   FROM appointments a 
                                   LEFT JOIN doctors d ON a.doctor_id = d.doctor_id 
                                   WHERE a.appointment_id = $appointment_id")->fetch_assoc();
        $patient_id = $appt_info['patient_id'];
        $doctor_name = $appt_info['doctor_name'] ?? 'the doctor';
        $appointment_date = date('M d, Y', strtotime($appt_info['appointment_date']));
        $appointment_time = date('h:i A', strtotime($appt_info['appointment_time']));
        
        $stmt = $conn->prepare("UPDATE appointments SET status = ? WHERE appointment_id = ?");
        $stmt->bind_param("si", $new_status, $appointment_id);
        if ($stmt->execute()) {
            $msg = "Appointment status updated to: " . $new_status;
            
            // Send notification based on status change
            if ($new_status == 'confirmed') {
                sendPatientNotification($patient_id, 'Appointment Confirmed', 'Your appointment with Dr. ' . $doctor_name . ' on ' . $appointment_date . ' at ' . $appointment_time . ' has been confirmed.', 'success');
            } elseif ($new_status == 'cancelled') {
                sendPatientNotification($patient_id, 'Appointment Cancelled', 'Your appointment on ' . $appointment_date . ' at ' . $appointment_time . ' has been cancelled. Please book a new appointment if needed.', 'danger');
            } elseif ($new_status == 'completed') {
                sendPatientNotification($patient_id, 'Appointment Completed', 'Your appointment on ' . $appointment_date . ' has been marked as completed. Thank you for using UHD.', 'success');
            }
        } else {
            $error = "Update failed: " . $conn->error;
        }
        $stmt->close();
    }
    
    // Handle doctor assignment
    if (isset($_POST['assign_doctor'])) {
        $appointment_id = (int)$_POST['appointment_id'];
        $doctor_id = (int)$_POST['doctor_id'];
        
        // Get patient info and doctor info before update
        $appt_info = $conn->query("SELECT a.patient_id, a.appointment_date, a.appointment_time 
                                   FROM appointments a 
                                   WHERE a.appointment_id = $appointment_id")->fetch_assoc();
        $patient_id = $appt_info['patient_id'];
        $appointment_date = date('M d, Y', strtotime($appt_info['appointment_date']));
        $appointment_time = date('h:i A', strtotime($appt_info['appointment_time']));
        
        $doctor_info = $conn->query("SELECT name FROM doctors WHERE doctor_id = $doctor_id")->fetch_assoc();
        $doctor_name = $doctor_info['name'];
        
        $stmt = $conn->prepare("UPDATE appointments SET doctor_id = ?, status = 'confirmed' WHERE appointment_id = ?");
        $stmt->bind_param("ii", $doctor_id, $appointment_id);
        if ($stmt->execute()) {
            $msg = "Doctor assigned and appointment confirmed!";
            
            // Send notification to patient
            sendPatientNotification($patient_id, 'Appointment Confirmed', 'Your appointment has been confirmed with Dr. ' . $doctor_name . ' on ' . $appointment_date . ' at ' . $appointment_time . '.', 'success');
            
            // Send notification to doctor (optional)
            // sendDoctorNotification($doctor_id, 'New Appointment Assigned', 'You have a new appointment with patient on ' . $appointment_date . ' at ' . $appointment_time, 'info');
            
        } else {
            $error = "Assignment failed: " . $conn->error;
        }
        $stmt->close();
    }
}

// Fetch all appointments with patient info
$appointments = $conn->query("
    SELECT a.*, 
           p.first_name, p.last_name, p.email, p.phone,
           d.name as doctor_name
    FROM appointments a 
    JOIN patients p ON a.patient_id = p.patient_id 
    LEFT JOIN doctors d ON a.doctor_id = d.doctor_id 
    ORDER BY a.appointment_date DESC
");

// Get list of doctors for assignment
$doctors = $conn->query("SELECT doctor_id, name, specialization FROM doctors WHERE status = 'active'");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Appointments - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <style>
        body { background: #0a3d2f; font-family: 'Segoe UI', sans-serif; }
        .navbar { background: #064e3b !important; }
        .card { border-radius: 20px; background: rgba(255,255,255,0.95); }
        .status-pending { background: #ffc107; color: #000; padding: 5px 10px; border-radius: 20px; font-size: 12px; display: inline-block; }
        .status-confirmed { background: #28a745; color: white; padding: 5px 10px; border-radius: 20px; font-size: 12px; display: inline-block; }
        .status-completed { background: #17a2b8; color: white; padding: 5px 10px; border-radius: 20px; font-size: 12px; display: inline-block; }
        .status-cancelled { background: #dc3545; color: white; padding: 5px 10px; border-radius: 20px; font-size: 12px; display: inline-block; }
    </style>
</head>
<body>
<nav class="navbar navbar-dark">
    <div class="container">
        <span class="navbar-brand"><i class="fas fa-calendar-alt"></i> Manage Appointments</span>
        <a href="dashboard.php" class="btn btn-light btn-sm">Back to Dashboard</a>
    </div>
</nav>

<div class="container mt-4">
    <div class="card">
        <div class="card-header bg-success text-white">
            <h5 class="mb-0"><i class="fas fa-list"></i> All Appointments</h5>
        </div>
        <div class="card-body">
            <?php if($msg): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <?= htmlspecialchars($msg) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            <?php if($error): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <?= htmlspecialchars($error) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <div class="table-responsive">
                <table class="table table-bordered table-hover">
                    <thead class="table-dark">
                        <tr>
                            <th>ID</th>
                            <th>Patient</th>
                            <th>Date & Time</th>
                            <th>Reason</th>
                            <th>Doctor</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if($appointments && $appointments->num_rows > 0): ?>
                            <?php while($a = $appointments->fetch_assoc()): ?>
                                <tr>
                                    <td><?= $a['appointment_id'] ?></td>
                                    <td>
                                        <strong><?= htmlspecialchars($a['first_name'] . ' ' . $a['last_name']) ?></strong><br>
                                        <small><?= htmlspecialchars($a['email']) ?></small>
                                    </td>
                                    <td>
                                        <?= date('M d, Y', strtotime($a['appointment_date'])) ?><br>
                                        <small><?= date('h:i A', strtotime($a['appointment_time'])) ?></small>
                                    </td>
                                    <td><?= htmlspecialchars(substr($a['reason'] ?? '', 0, 50)) ?>...</td>
                                    <td>
                                        <?php if($a['doctor_name']): ?>
                                            Dr. <?= htmlspecialchars($a['doctor_name']) ?>
                                        <?php else: ?>
                                            <span class="text-muted">Not assigned</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="status-<?= $a['status'] ?>">
                                            <?= ucfirst($a['status']) ?>
                                        </span>
                                    </td>
                                    <td>
                                        <!-- Update Status Dropdown -->
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="appointment_id" value="<?= $a['appointment_id'] ?>">
                                            <select name="status" class="form-select form-select-sm" onchange="this.form.submit()" style="width: auto; display: inline-block;">
                                                <option value="pending" <?= $a['status']=='pending' ? 'selected' : '' ?>>Pending</option>
                                                <option value="confirmed" <?= $a['status']=='confirmed' ? 'selected' : '' ?>>Confirmed</option>
                                                <option value="completed" <?= $a['status']=='completed' ? 'selected' : '' ?>>Completed</option>
                                                <option value="cancelled" <?= $a['status']=='cancelled' ? 'selected' : '' ?>>Cancelled</option>
                                            </select>
                                            <input type="hidden" name="update_status" value="1">
                                        </form>
                                        
                                        <!-- Assign Doctor Button -->
                                        <?php if($a['status'] == 'pending' || !$a['doctor_name']): ?>
                                            <button class="btn btn-primary btn-sm mt-1" data-bs-toggle="modal" data-bs-target="#assignModal<?= $a['appointment_id'] ?>">
                                                <i class="fas fa-user-md"></i> Assign Doctor
                                            </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                
                                <!-- Assign Doctor Modal -->
                                <div class="modal fade" id="assignModal<?= $a['appointment_id'] ?>" tabindex="-1">
                                    <div class="modal-dialog modal-dialog-centered">
                                        <div class="modal-content">
                                            <div class="modal-header bg-primary text-white">
                                                <h5>Assign Doctor</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                            </div>
                                            <form method="POST">
                                                <div class="modal-body">
                                                    <p><strong>Patient:</strong> <?= htmlspecialchars($a['first_name'] . ' ' . $a['last_name']) ?></p>
                                                    <p><strong>Date:</strong> <?= date('M d, Y', strtotime($a['appointment_date'])) ?> at <?= date('h:i A', strtotime($a['appointment_time'])) ?></p>
                                                    <div class="mb-3">
                                                        <label>Select Doctor</label>
                                                        <select name="doctor_id" class="form-control" required>
                                                            <option value="">-- Select Doctor --</option>
                                                            <?php 
                                                            $docs = $conn->query("SELECT doctor_id, name, specialization FROM doctors WHERE status = 'active'");
                                                            while($d = $docs->fetch_assoc()): 
                                                            ?>
                                                                <option value="<?= $d['doctor_id'] ?>">
                                                                    Dr. <?= htmlspecialchars($d['name']) ?> (<?= htmlspecialchars($d['specialization']) ?>)
                                                                </option>
                                                            <?php endwhile; ?>
                                                        </select>
                                                    </div>
                                                    <input type="hidden" name="appointment_id" value="<?= $a['appointment_id'] ?>">
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                    <button type="submit" name="assign_doctor" class="btn btn-primary">Assign & Confirm</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr><td colspan="7" class="text-center">No appointments found.<?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>