<?php
// api/create_schedule_api.php
// This API handles the creation of a new schedule and sends notifications.
// It is designed to be called via AJAX.

header('Content-Type: application/json');

// Ensure session is started for user authentication.
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Redirect if not logged in or not an admin/instructor.
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'instructor')) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Authentication required or not authorized.']);
    exit();
}

// Include necessary files
require_once '../config/database.php';
require_once '../vendor/autoload.php'; // Path to PHPMailer via Composer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// --- 1. EMAIL-SENDING FUNCTION ---
function sendScheduleEmail(array $student_data, array $schedule_data): bool {
    try {
        $mail = new PHPMailer(true);
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com'; 
        $mail->SMTPAuth   = true;
        // !!! SMTP CREDENTIALS FILLED IN !!!
        $mail->Username   = 'bazithali95@gmail.com'; 
        $mail->Password   = 'sqkt opow cvao fiac'; 
        // !!! END SMTP CONFIG !!!
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; 
        $mail->Port       = 587;
        
        $mail->setFrom('bazithali95@gmail.com', 'Orinsto LMS Administration');
        $mail->addAddress($student_data['email'], $student_data['full_name']);
        
        $mail->isHTML(true);
        $mail->Subject = "New Class Scheduled for {$schedule_data['batch_name']}";
        $mail->Body    = "
            <p>Dear " . htmlspecialchars($student_data['full_name']) . ",</p>
            <p>A new class has been scheduled for your course **" . htmlspecialchars($schedule_data['course_name']) . "** in the **" . htmlspecialchars($schedule_data['batch_name']) . "** batch.</p>
            <p><strong>Topic:</strong> " . htmlspecialchars($schedule_data['topic']) . "</p>
            <p><strong>Date:</strong> " . date('F d, Y', strtotime($schedule_data['schedule_date'])) . "</p>
            <p><strong>Time:</strong> " . date('h:i A', strtotime($schedule_data['start_time'])) . " - " . date('h:i A', strtotime($schedule_data['end_time'])) . "</p>
            <p><strong>Location/Link:</strong> " . htmlspecialchars($schedule_data['location_or_link']) . "</p>
            <p style='margin-top: 25px;'>Please check your dashboard for more details. We look forward to seeing you there!</p>
        ";
        $mail->AltBody = "New Class Scheduled! Topic: {$schedule_data['topic']} on {$schedule_data['schedule_date']} from {$schedule_data['start_time']} to {$schedule_data['end_time']}. Please check your LMS dashboard for more details.";
        
        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Email sending failed to {$student_data['email']}. Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}
// --- END OF EMAIL-SENDING FUNCTION ---

// Retrieve data from the POST request
$batch_id = trim($_POST['batch_id'] ?? '');
$schedule_date = trim($_POST['schedule_date'] ?? '');
$start_time = trim($_POST['start_time'] ?? '');
$end_time = trim($_POST['end_time'] ?? '');
$topic = trim($_POST['topic'] ?? '');
$location_or_link = trim($_POST['location_or_link'] ?? '');

$response = ['success' => false, 'message' => ''];

// --- 2. Input Validation and Batch Verification ---
if (empty($batch_id) || empty($schedule_date) || empty($start_time) || empty($end_time) || empty($topic)) {
    http_response_code(400);
    $response['message'] = "Please fill in all required fields.";
    echo json_encode($response);
    exit();
} elseif (strtotime($start_time) >= strtotime($end_time)) {
    http_response_code(400);
    $response['message'] = "End time must be after the start time.";
    echo json_encode($response);
    exit();
}

try {
    $pdo->beginTransaction();

    // Fetch batch details and verify ownership. This is crucial for security.
    $stmt = $pdo->prepare("
        SELECT b.id, b.batch_name, c.course_name, b.instructor_id
        FROM batches b
        JOIN courses c ON b.course_id = c.id
        WHERE b.id = ?
    ");
    $stmt->execute([$batch_id]);
    $batch = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$batch) {
        throw new Exception("The selected batch does not exist.");
    } elseif ($_SESSION['user_role'] === 'instructor' && $batch['instructor_id'] != $_SESSION['user_id']) {
        throw new Exception("You do not have permission to manage this batch.");
    }
    
    // --- 3. Insert the new schedule entry ---
    $stmt = $pdo->prepare("INSERT INTO batch_schedules (batch_id, schedule_date, start_time, end_time, topic, location_or_link) VALUES (?, ?, ?, ?, ?, ?)");
    if (!$stmt->execute([$batch_id, $schedule_date, $start_time, $end_time, $topic, $location_or_link])) {
        throw new Exception("Error inserting schedule into the database.");
    }
    $schedule_id = $pdo->lastInsertId();

    // --- 4. Retrieve students for notifications and emails ---
    $stmt_students = $pdo->prepare("
        SELECT ce.student_id, u.email, u.full_name
        FROM course_enrollments ce
        JOIN users u ON ce.student_id = u.id
        WHERE ce.batch_id = ? AND ce.status = 'enrolled'
    ");
    $stmt_students->execute([$batch_id]);
    $enrolled_students = $stmt_students->fetchAll(PDO::FETCH_ASSOC);

    // --- 5. Insert notifications and send emails ---
    $notif_title = "🗓️ New Class Scheduled!";
    $notif_message = "A new class, **\"" . htmlspecialchars($topic) . "\"**, has been scheduled for your batch **" . htmlspecialchars($batch['batch_name']) . "** on " . date('M d, Y', strtotime($schedule_date)) . " from " . date('h:i A', strtotime($start_time)) . ".";
    
    $sql_notify = "INSERT INTO notifications (user_id, type, title, message, related_id) VALUES (?, 'schedule', ?, ?, ?)";
    $stmt_notify = $pdo->prepare($sql_notify);

    $schedule_data = [
        'batch_name' => $batch['batch_name'],
        'course_name' => $batch['course_name'],
        'schedule_date' => $schedule_date,
        'start_time' => $start_time,
        'end_time' => $end_time,
        'topic' => $topic,
        'location_or_link' => $location_or_link
    ];

    foreach ($enrolled_students as $student) {
        // Insert internal notification
        $stmt_notify->execute([$student['student_id'], $notif_title, $notif_message, $schedule_id]);

        // Send email notification
        sendScheduleEmail($student, $schedule_data);
    }

    $pdo->commit();
    $response['success'] = true;
    $response['message'] = "Schedule entry added successfully! " . count($enrolled_students) . " students have been notified via the LMS and email. ✅";

} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(500);
    $response['message'] = "Error: " . $e->getMessage();
    error_log("Schedule API Error: " . $e->getMessage());

} catch (PDOException $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(500);
    $response['message'] = "Database error: " . $e->getMessage();
    error_log("Schedule PDO Error: " . $e->getMessage());
}

echo json_encode($response);
exit();