<?php 
// Filename: booking/my_bookings.php
include '../config.php'; 

// SECURITY: Ensure User ID exists
requireLogin();

$teacher_id = $_SESSION['user_id'];

// --- 1. HANDLE CANCELLATION ---
if (isset($_GET['cancel_id'])) {
    $cancel_id = intval($_GET['cancel_id']);
    // Security: Only allow cancelling OWN pending requests
    $stmt = $pdo->prepare("DELETE FROM bookings WHERE id = ? AND teacher_id = ? AND status = 'pending'");
    $stmt->execute([$cancel_id, $teacher_id]);
    
    if ($stmt->rowCount() > 0) {
        $msg = "Request cancelled successfully."; $msg_type = "success";
    } else {
        $msg = "Could not cancel. It may have been processed already."; $msg_type = "danger";
    }
}

// --- 2. GET USER & THEME DATA ---
// Using PDO prepare/execute
$u_stmt = $pdo->prepare("SELECT full_name, avatar FROM users WHERE id = ?");
$u_stmt->execute([$teacher_id]);
$user_data = $u_stmt->fetch(PDO::FETCH_ASSOC);

$full_name = $user_data['full_name'] ?? 'User';
$user_avatar = $user_data['avatar'] ?? '';

// Get Theme
$theme_setting = getSetting('header_theme', 'default');

// Map Theme to Gradient
$gradients = [
    'default' => 'linear-gradient(135deg, #6366f1 0%, #8B5CF6 100%)',
    'blue'    => 'linear-gradient(135deg, #3b82f6 0%, #0ea5e9 100%)',
    'red'     => 'linear-gradient(135deg, #ef4444 0%, #b91c1c 100%)',
    'sunny'   => 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)',
    'rainy'   => 'linear-gradient(135deg, #64748b 0%, #334155 100%)',
    'dark'    => 'linear-gradient(135deg, #1e293b 0%, #0f172a 100%)'
];
$active_grad = $gradients[$theme_setting] ?? $gradients['default'];

// --- 3. GET STATS ---
$sql_stats = "SELECT 
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN status = 'approved' THEN 1 ELSE 0 END) as approved,
    SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected
    FROM bookings WHERE teacher_id = ?";
$s_stmt = $pdo->prepare($sql_stats);
$s_stmt->execute([$teacher_id]);
$stats = $s_stmt->fetch(PDO::FETCH_ASSOC);

// --- 4. FETCH BOOKINGS LIST ---
$sql = "SELECT b.*, r.name as room_name 
        FROM bookings b 
        JOIN rooms r ON b.room_id = r.id 
        WHERE b.teacher_id = ? 
        ORDER BY b.booking_date DESC, b.start_time ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute([$teacher_id]);
$bookings = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Bookings</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        :root { 
            --primary-grad: <?= $active_grad ?>; 
            --bg-color: #f8f9fd; 
            --text-dark: #1e293b; 
        }
        
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 90px; }
        
        /* HEADER */
        .app-header { background: var(--primary-grad); padding: 20px 20px 80px 20px; border-radius: 0 0 35px 35px; color: white; position: relative; }
        .header-top { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 20px; }
        .avatar-ring { border: 2px solid rgba(255,255,255,0.8); padding: 2px; border-radius: 50%; width: 54px; height: 54px; }
        .avatar-img { width: 100%; height: 100%; border-radius: 50%; object-fit: cover; background: #fff; }
        
        /* FLOATING STATS CARD */
        .floating-card { background: white; margin: -60px 20px 20px 20px; border-radius: 24px; padding: 20px; box-shadow: 0 15px 35px rgba(0,0,0,0.08); position: relative; z-index: 10; }
        
        .stat-item { text-align: center; padding: 10px; border-radius: 16px; border: 1px solid #f1f5f9; background: #f8fafc; }
        .stat-val { font-size: 1.5rem; font-weight: 800; line-height: 1; margin-bottom: 5px; }
        .stat-label { font-size: 0.65rem; color: #64748b; font-weight: 700; text-transform: uppercase; }

        /* LIST CARD */
        .dashboard-card { background: white; border: none; border-radius: 20px; box-shadow: 0 5px 20px rgba(0,0,0,0.05); margin: 0 20px; overflow: hidden; }
        
        .list-group-item { border: none; border-bottom: 1px solid #f1f5f9; padding: 15px; transition: 0.2s; }
        .list-group-item:last-child { border-bottom: none; }
        .list-group-item:hover { background: #f8fafc; }

        /* BADGES */
        .badge-pending { background: #fffbeb; color: #d97706; border: 1px solid #fef3c7; }
        .badge-approved { background: #f0fdf4; color: #16a34a; border: 1px solid #dcfce7; }
        .badge-rejected { background: #fef2f2; color: #ef4444; border: 1px solid #fee2e2; }
    </style>
</head>
<body>

    <div class="app-header">
        <div class="header-top">
            <a href="index.php" class="text-white text-decoration-none opacity-75"><i class="bi bi-arrow-left fs-4"></i> Back</a>
            <div class="opacity-50"><i class="bi bi-calendar-check"></i> History</div>
        </div>
        <div class="d-flex align-items-center">
            <div class="avatar-ring me-3">
                <?php if(!empty($user_avatar)): ?><img src="../<?= $user_avatar ?>" class="avatar-img"><?php else: ?><div class="avatar-img d-flex align-items-center justify-content-center text-primary fw-bold bg-white"><?= substr($full_name,0,1) ?></div><?php endif; ?>
            </div>
            <div>
                <div class="opacity-75 small">My Requests</div>
                <h5 class="mb-0 fw-bold"><?= htmlspecialchars($full_name) ?></h5>
            </div>
        </div>
    </div>

    <div class="floating-card">
        <?php if(isset($msg)): ?><div class="alert alert-<?= $msg_type ?> border-0 text-center py-2 small mb-3"><?= $msg ?></div><?php endif; ?>
        
        <div class="row g-2">
            <div class="col-4">
                <div class="stat-item">
                    <div class="stat-val text-warning"><?= intval($stats['pending'] ?? 0) ?></div>
                    <div class="stat-label">Pending</div>
                </div>
            </div>
            <div class="col-4">
                <div class="stat-item">
                    <div class="stat-val text-success"><?= intval($stats['approved'] ?? 0) ?></div>
                    <div class="stat-label">Approved</div>
                </div>
            </div>
            <div class="col-4">
                <div class="stat-item">
                    <div class="stat-val text-danger"><?= intval($stats['rejected'] ?? 0) ?></div>
                    <div class="stat-label">Rejected</div>
                </div>
            </div>
        </div>
    </div>

    <div class="container px-4 mb-3">
        <h6 class="fw-bold text-muted small text-uppercase">Request History</h6>
    </div>

    <div class="dashboard-card mb-4">
        <?php if (count($bookings) > 0): ?>
            <div class="list-group list-group-flush">
                <?php foreach($bookings as $row): ?>
                    <?php
                        // Status Logic
                        $status_cls = 'badge-pending';
                        $status_icon = 'bi-hourglass-split';
                        if ($row['status'] == 'approved') { $status_cls = 'badge-approved'; $status_icon = 'bi-check-circle-fill'; }
                        if ($row['status'] == 'rejected') { $status_cls = 'badge-rejected'; $status_icon = 'bi-x-circle-fill'; }
                        
                        $date_nice = date("d M Y", strtotime($row['booking_date']));
                        $time_nice = date("h:i A", strtotime($row['start_time'])) . ' - ' . date("h:i A", strtotime($row['end_time']));
                    ?>
                    <div class="list-group-item">
                        <div class="d-flex w-100 justify-content-between align-items-center mb-1">
                            <span class="badge bg-light text-dark border"><?= htmlspecialchars($row['room_name']) ?></span>
                            <span class="badge <?= $status_cls ?> rounded-pill px-2">
                                <i class="bi <?= $status_icon ?> me-1"></i> <?= strtoupper($row['status']) ?>
                            </span>
                        </div>
                        
                        <div class="d-flex justify-content-between align-items-end mt-2">
                            <div>
                                <h6 class="mb-0 fw-bold text-dark"><?= $date_nice ?></h6>
                                <small class="text-muted d-block"><?= $time_nice ?></small>
                                <small class="d-block mt-1 text-muted fst-italic">"<?= htmlspecialchars($row['purpose']) ?>"</small>
                            </div>

                            <?php if ($row['status'] == 'pending'): ?>
                                <div>
                                    <a href="my_bookings.php?cancel_id=<?= $row['id'] ?>" 
                                       class="btn btn-outline-danger btn-sm rounded-pill fw-bold"
                                       style="font-size: 0.75rem;"
                                       onclick="return confirm('Cancel this request?');">
                                       Cancel
                                    </a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="text-center py-5">
                <i class="bi bi-calendar-x fs-1 opacity-25 d-block mb-3"></i>
                <p class="text-muted small">You haven't made any bookings yet.</p>
                <a href="index.php" class="btn btn-primary btn-sm rounded-pill px-4">Book a Room</a>
            </div>
        <?php endif; ?>
    </div>
    
    <?php include '../menu.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>