<?php
session_start();
require 'db.php';

if (!isset($_SESSION['student_id'])) {
    header("Location: login.php");
    exit();
}

$student_id = $_SESSION['student_id'];
$name = $_SESSION['student_name'] ?? 'Student';
$success = "";
$error = "";

// Handle cancellation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cancel_slot_id'])) {
    $slot_id = $_POST['cancel_slot_id'];

    $stmt = $conn->prepare("
        SELECT ia.available_date, ia.start_time
        FROM InstructorAvailability ia
        JOIN BookedDrives bd ON ia.id = bd.slot_id
        WHERE bd.student_id = ? AND bd.slot_id = ?
    ");
    $stmt->bind_param("ii", $student_id, $slot_id);
    $stmt->execute();
    $stmt->bind_result($date, $time);
    if ($stmt->fetch()) {
        $scheduled_datetime = strtotime("$date $time");
        $now = time();
        if (($scheduled_datetime - $now) < 21600) { // less than 6 hours
            $reason = "Late cancellation by student";
            $fee = 35.00;
            $recorded_by = "system";

            $stmt->close();
            $stmt = $conn->prepare("INSERT INTO NoShows (student_id, date, reason, fee, recorded_by) VALUES (?, ?, ?, ?, ?)");
            $date_now = date('Y-m-d');
            $stmt->bind_param("issds", $student_id, $date_now, $reason, $fee, $recorded_by);
            $stmt->execute();
        }

        // Remove the booking
        $stmt->close();
        $stmt = $conn->prepare("DELETE FROM BookedDrives WHERE student_id = ? AND slot_id = ?");
        $stmt->bind_param("ii", $student_id, $slot_id);
        $stmt->execute();
        $success = "Drive canceled successfully.";
    } else {
        $error = "Drive not found or already canceled.";
    }
    $stmt->close();
}

// Fetch student's booked drives
$stmt = $conn->prepare("
    SELECT bd.slot_id, ia.available_date, ia.start_time, ia.end_time, i.first_name, i.last_name
    FROM BookedDrives bd
    JOIN InstructorAvailability ia ON bd.slot_id = ia.id
    JOIN Instructors i ON ia.instructor_id = i.id
    WHERE bd.student_id = ?
    ORDER BY ia.available_date ASC, ia.start_time ASC
");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$result = $stmt->get_result();
$booked_drives = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Student Dashboard</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            padding: 40px;
            background: url('hotrod-1.jpg') no-repeat center center fixed;
            background-size: cover;
        }
        .dashboard {
            background: rgba(255,255,255,0.95);
            padding: 30px;
            border-radius: 10px;
            display: inline-block;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            background: #fff;
        }
        th, td {
            padding: 10px;
            border: 1px solid #ddd;
        }
        th {
            background-color: #eee;
        }
        .btn-cancel {
            padding: 6px 12px;
            background: #d9534f;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        .message {
            margin-bottom: 20px;
            font-weight: bold;
        }
        .success { color: green; }
        .error { color: red; }
    </style>
</head>
<body>
    <div class="dashboard">
        <h2>Welcome, <?= htmlspecialchars($name) ?></h2>
        <div style="margin: 20px 0;">
    <a href="student-drive-booking.php" style="padding: 10px 20px; background-color: #007bff; color: white; text-decoration: none; border-radius: 5px; margin-right: 10px;">Book a Drive</a>
    <a href="student-login.php" style="padding: 10px 20px; background-color: #6c757d; color: white; text-decoration: none; border-radius: 5px;">Log Out</a>
</div>

        <h3>Upcoming Drives</h3>

        <?php if ($success): ?><div class="message success"><?= $success ?></div><?php endif; ?>
        <?php if ($error): ?><div class="message error"><?= $error ?></div><?php endif; ?>

        <?php if (count($booked_drives) > 0): ?>
        <table>
            <tr>
                <th>Date</th>
                <th>Time</th>
                <th>Instructor</th>
                <th>Action</th>
            </tr>
            <?php foreach ($booked_drives as $drive): ?>
                <tr>
                    <td><?= htmlspecialchars($drive['available_date']) ?></td>
                    <td><?= htmlspecialchars($drive['start_time'] . ' - ' . $drive['end_time']) ?></td>
                    <td><?= htmlspecialchars($drive['first_name'] . ' ' . $drive['last_name']) ?></td>
                    <td>
                        <form method="post" onsubmit="return confirm('Are you sure you want to cancel this drive?');">
                            <input type="hidden" name="cancel_slot_id" value="<?= $drive['slot_id'] ?>">
                            <button type="submit" class="btn-cancel">Cancel</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
        </table>
        <?php else: ?>
            <p>No upcoming drives scheduled.</p>
        <?php endif; ?>
        <hr><br>
<h3>Drive History</h3>
<?php
// Fetch past drives
$stmt = $conn->prepare("
    SELECT drive_date, drive_type, minutes
    FROM DriveSchedule
    WHERE student_id = ? AND drive_date < CURDATE()
    ORDER BY drive_date DESC
");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$drive_result = $stmt->get_result();
$total_minutes = 0;
?>

<?php if ($drive_result->num_rows > 0): ?>
<table>
    <tr>
        <th>Date</th>
        <th>Type</th>
        <th>Minutes</th>
    </tr>
    <?php while ($row = $drive_result->fetch_assoc()): 
        $total_minutes += $row['minutes']; ?>
        <tr>
            <td><?= htmlspecialchars($row['drive_date']) ?></td>
            <td><?= htmlspecialchars($row['drive_type']) ?></td>
            <td><?= htmlspecialchars($row['minutes']) ?></td>
        </tr>
    <?php endwhile; ?>
</table>
<p><strong>Total Minutes Completed:</strong> <?= $total_minutes ?></p>
<?php else: ?>
<p>No previous drives logged.</p>
<?php endif; ?>
<?php $stmt->close(); ?>

<br>
<h3>No-Shows & Fees</h3>
<?php
// Fetch no-shows
$stmt = $conn->prepare("
    SELECT date, reason, fee
    FROM NoShows
    WHERE student_id = ?
    ORDER BY date DESC
");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$ns_result = $stmt->get_result();
$total_fees = 0;
?>

<?php if ($ns_result->num_rows > 0): ?>
<table>
    <tr>
        <th>Date</th>
        <th>Reason</th>
        <th>Fee</th>
    </tr>
    <?php while ($row = $ns_result->fetch_assoc()):
        $total_fees += $row['fee']; ?>
        <tr>
            <td><?= htmlspecialchars($row['date']) ?></td>
            <td><?= htmlspecialchars($row['reason']) ?></td>
            <td>$<?= number_format($row['fee'], 2) ?></td>
        </tr>
    <?php endwhile; ?>
</table>
<p><strong>Total Fees Owed:</strong> $<?= number_format($total_fees, 2) ?></p>
<?php else: ?>
<p>No no-shows recorded.</p>
<?php endif; ?>
    <?php $stmt->close(); ?>
    </div>
</body>
</html>
