<?php
require_once '../config.php';

// Ensure session is started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if user is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: ' . BASE_URL . '/admin/login');
    exit;
}

$conn = get_db_connection();
$message = '';
$message_type = '';

// Handle Status Update
if (isset($_POST['update_status'])) {
    $id = (int) $_POST['appointment_id'];
    $status = $_POST['status'];

    $stmt = $conn->prepare("UPDATE appointments SET status = ? WHERE id = ?");
    $stmt->bind_param("si", $status, $id);
    if ($stmt->execute()) {
        $message = "Appointment status updated successfully.";
        $message_type = "success";
    } else {
        $message = "Error updating status.";
        $message_type = "danger";
    }
    $stmt->close();
}

// Handle Delete
if (isset($_POST['delete_appointment'])) {
    $id = (int) $_POST['appointment_id'];
    $stmt = $conn->prepare("DELETE FROM appointments WHERE id = ?");
    $stmt->bind_param("i", $id);
    if ($stmt->execute()) {
        $message = "Appointment deleted successfully.";
        $message_type = "success";
    } else {
        $message = "Error deleting appointment.";
        $message_type = "danger";
    }
    $stmt->close();
}

// Fetch Appointments
$result = $conn->query("SELECT * FROM appointments ORDER BY created_at DESC");
$appointments = [];
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $appointments[] = $row;
    }
}

$page_title = 'Manage Appointments';
require_once 'includes/admin-header.php';
?>

<?php if ($message): ?>
    <div class="alert alert-<?php echo $message_type; ?>">
        <i class="fas fa-<?php echo $message_type === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
        <?php echo htmlspecialchars($message); ?>
    </div>
<?php endif; ?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Customer Appointments</h2>
        <div class="card-tools">
            <span class="badge badge-info">
                <?php echo count($appointments); ?> Total
            </span>
        </div>
    </div>

    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th>Customer</th>
                    <th>Contact</th>
                    <th>Service</th>
                    <th>Date & Time</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($appointments)): ?>
                    <tr>
                        <td colspan="6" style="text-align: center; padding: 40px; color: var(--text-muted);">
                            <i class="fas fa-calendar-times"
                                style="font-size: 48px; margin-bottom: 16px; display: block; opacity: 0.3;"></i>
                            No appointments found.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($appointments as $app): ?>
                        <tr>
                            <td data-label="Customer">
                                <div style="font-weight: 600; color: var(--dark);">
                                    <?php echo htmlspecialchars($app['first_name'] . ' ' . $app['last_name']); ?>
                                </div>
                                <div style="font-size: 12px; color: var(--text-muted);">
                                    <i class="fas fa-map-marker-alt" style="width: 14px;"></i>
                                    <?php echo htmlspecialchars($app['address']); ?>
                                </div>
                            </td>
                            <td data-label="Contact">
                                <div style="font-size: 14px;">
                                    <i class="fas fa-phone" style="width: 14px; color: var(--secondary);"></i>
                                    <?php echo htmlspecialchars($app['phone']); ?>
                                </div>
                                <div style="font-size: 14px;">
                                    <i class="fas fa-envelope" style="width: 14px; color: var(--secondary);"></i>
                                    <?php echo htmlspecialchars($app['email']); ?>
                                </div>
                            </td>
                            <td data-label="Service">
                                <span class="badge badge-info" style="background: var(--primary-light); color: var(--primary);">
                                    <?php echo htmlspecialchars($app['service']); ?>
                                </span>
                            </td>
                            <td data-label="Date & Time">
                                <div style="font-weight: 500;">
                                    <?php echo date('M d, Y', strtotime($app['appointment_date'])); ?>
                                </div>
                                <div style="font-size: 13px; color: var(--text-muted);">
                                    <?php echo date('h:i A', strtotime($app['appointment_time'])); ?>
                                </div>
                            </td>
                            <td data-label="Status">
                                <?php
                                $status_class = '';
                                switch ($app['status']) {
                                    case 'pending':
                                        $status_class = 'badge-warning';
                                        break;
                                    case 'confirmed':
                                        $status_class = 'badge-info';
                                        break;
                                    case 'completed':
                                        $status_class = 'badge-success';
                                        break;
                                    case 'cancelled':
                                        $status_class = 'badge-danger';
                                        break;
                                }
                                ?>
                                <span class="badge <?php echo $status_class; ?>">
                                    <?php echo ucfirst($app['status']); ?>
                                </span>
                            </td>
                            <td data-label="Actions">
                                <div style="display: flex; gap: 8px;">
                                    <form method="POST" style="display: inline-flex; gap: 4px;">
                                        <input type="hidden" name="appointment_id" value="<?php echo $app['id']; ?>">
                                        <select name="status" class="form-control"
                                            style="padding: 4px 8px; font-size: 12px; height: auto; width: 110px;">
                                            <option value="pending" <?php echo $app['status'] == 'pending' ? 'selected' : ''; ?>>
                                                Pending</option>
                                            <option value="confirmed" <?php echo $app['status'] == 'confirmed' ? 'selected' : ''; ?>>Confirmed</option>
                                            <option value="completed" <?php echo $app['status'] == 'completed' ? 'selected' : ''; ?>>Completed</option>
                                            <option value="cancelled" <?php echo $app['status'] == 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                                        </select>
                                        <button type="submit" name="update_status" class="btn btn-primary"
                                            style="padding: 4px 8px; font-size: 12px;">
                                            <i class="fas fa-check"></i>
                                        </button>
                                    </form>

                                    <form method="POST"
                                        onsubmit="return confirm('Are you sure you want to delete this appointment?');">
                                        <input type="hidden" name="appointment_id" value="<?php echo $app['id']; ?>">
                                        <button type="submit" name="delete_appointment" class="btn btn-danger"
                                            style="padding: 4px 10px; font-size: 12px;">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>



<?php require_once 'includes/admin-footer.php'; ?>