<?php
session_start();
require 'db.php';
require 'includes/PHPMailer/PHPMailer.php';
require 'includes/PHPMailer/SMTP.php';
require 'includes/PHPMailer/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$success = "";
$error = "";
// Set the 'minutes' column to match 'btw_minutes' for consistency
$minutes = $btw_minutes; // use this for the 'minutes' column


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

$instructor_id = $_SESSION['instructor_id'];
echo "<p>Logged in as instructor ID: $instructor_id</p>";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $student_id = $_POST['student_id'] ?? null;
    $btw_minutes = isset($_POST['btw_minutes']) ? intval($_POST['btw_minutes']) : 0;
    $ob_minutes  = isset($_POST['ob_minutes']) ? intval($_POST['ob_minutes']) : 0;
    $minutes     = $btw_minutes; // used for overall progress tracking
    $drive_date = $_POST['date'] ?? null;
    $scheduled_time = $_POST['scheduled_time'] ?? null;
    $lesson_group = isset($_POST['lesson_group']) ? trim($_POST['lesson_group']) : null;
    $lesson_status = isset($_POST['lesson_status']) ? trim($_POST['lesson_status']) : 'I';

$valid_statuses = ['I', 'F', 'P'];

if (!in_array($lesson_status, $valid_statuses)) {
    die("Invalid lesson status.");
}

    $check = $conn->prepare("SELECT * FROM DriveSchedule WHERE student_id = ? AND drive_type = ? AND drive_date = ?");
    $check->bind_param("iss", $student_id, $drive_type, $drive_date);
    $check->execute();
    $check_result = $check->get_result();

    if ($check_result->num_rows > 0) {
        $error = "This drive has already been logged.";
    } else {
        // Convert lesson_group code (e.g., 'lesson_3') to its numeric ID
        $lesson_group_id = null;
        $lookup = $conn->prepare("SELECT id FROM lesson_groups WHERE code = ?");
        $lookup->bind_param("s", $lesson_group);
        $lookup->execute();
        $lookup->bind_result($lesson_group_id);
        $lookup->fetch();
        $lookup->close();

        if (!$lesson_group_id) {
            die("Invalid lesson group selection.");
        }
        
        if (!$lesson_group_id || !$lesson_group) {
    die("Missing or invalid lesson group. Log aborted.");
}


        // Insert using the new lesson_group_id
        $stmt = $conn->prepare("INSERT INTO DriveSchedule 
    (student_id, instructor_id, scheduled_time, minutes, drive_date, lesson_group_id, lesson_status, btw_minutes, ob_minutes) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("iiiisisii", $student_id, $instructor_id, $scheduled_time, $minutes, $drive_date, $lesson_group_id, $lesson_status, $btw_minutes, $ob_minutes);

        $stmt->execute();

        if ($stmt->execute()) {
            $success = "Drive time logged successfully.";

            $email_stmt = $conn->prepare("SELECT email, first_name, last_name FROM Students WHERE id = ?");
            $email_stmt->bind_param("i", $student_id);
            $email_stmt->execute();
            $result = $email_stmt->get_result();
            $student = $result->fetch_assoc();

            if ($student) {
                $mail = new PHPMailer(true);
                try {
                    $mail->isSMTP();
                    $mail->Host = 'mail.tandddrivingacademy.com';
                    $mail->SMTPAuth = true;
                    $mail->Username = 'info@tandddrivingacademy.com';
                    $mail->Password = '!DriverightTX!';
                    $mail->SMTPSecure = 'ssl';
                    $mail->Port = 465;

                    $mail->setFrom('info@tandddrivingacademy.com', 'T&D Driving Academy');
                    $mail->addAddress($student['email'], $student['first_name'] . ' ' . $student['last_name']);

                    $mail->isHTML(true);
                    $mail->Subject = 'Drive Time Logged';
                    $mail->Body = "Dear {$student['first_name']} {$student['last_name']},<br><br>Your {$drive_type} drive time of {$minutes} minutes on {$drive_date} at {$scheduled_time} has been logged.<br><br>Thank you,<br>T&D Driving Academy";

                    $mail->send();
                } catch (Exception $e) {
                    error_log("Email could not be sent. Mailer Error: {$mail->ErrorInfo}");
                }
            }
        } else {
            $error = "Failed to log drive.";
        }
        $stmt->close();
    }
    $check->close();
}
?>
<?php 
    $lesson_groups = [];
    $result = $conn->query("SELECT code, label FROM lesson_groups ORDER BY id ASC");
    while ($row = $result->fetch_assoc()) {
    $lesson_groups[$row['code']] = $row['label'];
    }
    ?>
    
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Log Drive Time</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 30px;
        }
        .success {
            color: green;
            font-weight: bold;
            margin-bottom: 10px;
        }
        .error {
            color: red;
            font-weight: bold;
            margin-bottom: 10px;
        }
        form {
            max-width: 400px;
            margin-top: 20px;
        }
        input, select {
            width: 100%;
            margin: 8px 0;
            padding: 10px;
        }
        button {
            padding: 10px;
            margin: 5px 5px 0 0;
        }
        .container-flex {
            display: flex;
            gap: 40px;
            align-items: flex-start;
        }
        .form-container {
            flex: 1;
            max-width: 400px;
        }
        .lesson-history {
            flex: 1;
            border: 1px solid #ccc;
            padding: 15px;
            max-height: 400px;
            overflow-y: auto;
        }
        .lesson-history table {
            width: 100%;
            border-collapse: collapse;
        }
        .lesson-history th, .lesson-history td {
            padding: 8px;
            border: 1px solid #ccc;
            text-align: left;
        }
        .lesson-history h3 {
            margin-top: 0;
        }

    </style>
</head>
<body>

<h2>Log Student Drive Time</h2>

<?php if ($success): ?>
    <p class="success"><?php echo $success; ?></p>
    <form method="get" action="log-drive.php">
    <button type="submit" onclick="localStorage.removeItem('selectedStudent')">Log Another Drive</button>
        <a href="instructor-dashboard.php"><button type="button">Return to Dashboard</button></a>
    </form>
<?php elseif ($error): ?>
    <p class="error"><?php echo $error; ?></p>
    <form method="get" action="log-drive.php">
        <button type="submit">Try Again</button>
        <a href="instructor-dashboard.php"><button type="button">Return to Dashboard</button></a>
    </form>
    
<?php else: ?>

<?php

$student_id = isset($_POST['student_id']) ? intval($_POST['student_id']) : 0;
$incomplete_lessons = [];

$stmt = $conn->prepare("
    SELECT lg.code, lg.label
    FROM DriveSchedule ds
    INNER JOIN lesson_groups lg ON ds.lesson_group_id = lg.id
    WHERE ds.student_id = ? AND ds.lesson_status IN ('I', 'F')
");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    $incomplete_lessons[] = $row['code'];
}

if (empty($incomplete_lessons)) {
    // fallback to all lesson codes if none are incomplete yet
    $incomplete_lessons = array_keys($lesson_groups);
}

?>
<?php
$date_value = isset($_POST['date']) ? htmlspecialchars($_POST['date']) : '';
$time_value = isset($_POST['scheduled_time']) ? htmlspecialchars($_POST['scheduled_time']) : '';
?>
    <div class="container-flex">
        <div class="form-container">
            <form method="post">
                <!-- ... your form fields remain unchanged ... -->
                <!-- Just make sure student_id select box has id="student_id" -->
    
                <!-- Include both BTW and OB fields here (we'll update this next) -->
                
                <label for="student_id">Student:</label>
                <select name="student_id" id="student_id" required>
                    <option value="">Select a student</option>
                    <?php
                    $students = $conn->query("SELECT id, first_name, last_name FROM Students ORDER BY last_name ASC, first_name ASC");
                    while ($row = $students->fetch_assoc()) {
                        echo "<option value='{$row['id']}'>{$row['last_name']}, {$row['first_name']}</option>";
                    }
                    ?>
                </select>
    
                <!-- Keep the rest of your form as-is -->
    
            </form>
        </div>

    <div class="lesson-history" id="lesson-history">
        <h3>Completed Lessons</h3>
        <p>Select a student to view history...</p>
    </div>
</div>

    <?php if (!empty($_POST['student_id'])): ?>
    <input type="hidden" name="student_id" value="<?= htmlspecialchars($_POST['student_id']) ?>">
    <?php endif; ?>

    <label for="btw_minutes">Behind-the-Wheel Minutes:</label>
    <input type="number" name="btw_minutes" id="btw_minutes" min="0" max="120" step="5" placeholder="e.g., 40">

    <label for="ob_minutes">Observation Minutes:</label>
    <input type="number" name="ob_minutes" id="ob_minutes" min="0" max="120" step="5" placeholder="e.g., 80">

    
    <label for="lesson_group">Lesson Group Covered:</label>
    <select name="lesson_group" id="lesson_group" required>
        <option value="">-- Select a Lesson Group --</option>
    </select>
    
    <!-- Lesson options will be populated dynamically -->

    <label for="lesson_status">Result:</label>
    <select name="lesson_status" id="lesson_status" required>
        <option value="">-- Select Status --</option>
        <option value="P">Pass</option>
        <option value="F">Fail</option>
    </select>

    <label for="date">Drive Date:</label>
    <input type="date" name="date" value="<?= $date_value ?>" required>

    <label for="scheduled_time">Scheduled Time:</label>
    <input type="time" name="scheduled_time" value="<?= $time_value ?>" required>
    <form method="post" id="logDriveForm">
    <input type="submit" value="Log Drive Time" id="submitBtn">
</form>
<?php endif; ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const studentSelect = document.getElementById('student_id');
    const historyBox = document.getElementById('lesson-history');
    const lessonDropdown = document.getElementById('lesson_group');

    // Fetch completed lessons when a student is selected
    studentSelect.addEventListener('change', function () {
        const studentId = this.value;
        if (!studentId) return;

        // Fetch lesson history
        fetch(`fetch-lesson-history.php?student_id=${studentId}`)
            .then(res => res.json())
            .then(data => {
                if (!data || !Array.isArray(data.lessons)) {
                    historyBox.innerHTML = "<p>No history available.</p>";
                    return;
                }

                const total = data.total_btw ?? 0;
                let html = `<h3>Completed Lessons</h3>`;
                html += `<p><strong>Total BTW Minutes:</strong> ${total} / 385</p>`;

                if (data.lessons.length === 0) {
                    html += "<p>No completed lessons yet.</p>";
                } else {
                    html += `<table><thead><tr><th>Lesson</th><th>Times Covered</th></tr></thead><tbody>`;
                    data.lessons.forEach(entry => {
                        html += `<tr><td>${entry.label}</td><td>${entry.times_covered}</td></tr>`;
                    });
                    html += `</tbody></table>`;
                }

                historyBox.innerHTML = html;
            })
            .catch(error => {
                console.error("Lesson history fetch failed:", error);
                historyBox.innerHTML = "<p>Error loading lesson history.</p>";
            });
    });

    // Fetch lesson group options (ALWAYS all 10)
    fetch('fetch-lessons.php')
        .then(res => res.json())
        .then(data => {
            if (!lessonDropdown) return;
            lessonDropdown.innerHTML = '<option value="">-- Select a Lesson Group --</option>';
            data.forEach(lesson => {
                const opt = document.createElement('option');
                opt.value = lesson.code;
                opt.textContent = lesson.label;
                lessonDropdown.appendChild(opt);
            });
        })
        .catch(err => console.error("Lesson group fetch failed:", err));
});
</script>

<!-- Validation script for btw/ob minutes -->
<script>
document.getElementById('logDriveForm').addEventListener('submit', function (e) {
    const btw = parseInt(document.getElementById('btw_minutes').value) || 0;
    const ob = parseInt(document.getElementById('ob_minutes').value) || 0;

    if (btw === 0 && ob === 0) {
        e.preventDefault();
        alert("Please enter either Behind-the-Wheel minutes, Observation minutes, or both before logging the drive.");
    }
});
</script>
</body>
</html>



