<?php
// api/update_batch_schedule.php
// API endpoint to update an existing batch schedule entry.

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

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

// 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')) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access.']);
    exit();
}

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 sendScheduleUpdateEmail(array $student_data, array $schedule_data, string $message_details): 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 = "Schedule Update for Your Class: {$schedule_data['topic']}";
        $mail->Body     = "
            <p>Dear " . htmlspecialchars($student_data['full_name']) . ",</p>
            <p>An update has been made to the schedule for your course **" . htmlspecialchars($schedule_data['course_name']) . "** in the **" . htmlspecialchars($schedule_data['batch_name']) . "** batch.</p>
            
            <div style='padding: 10px; border: 1px solid #ddd; background-color: #f9f9f9;'>
                {$message_details}
            </div>

            <p style='margin-top: 25px;'>Please log in to your dashboard to view the full details.</p>
        ";
        $mail->AltBody = "An update has been made to the schedule for your course. Please log in to your dashboard for 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 ---

$input = json_decode(file_get_contents('php://input'), true);

$id = $input['id'] ?? null;
$batch_id = $input['batch_id'] ?? null;

// The rest of the fields are now optional
$schedule_date = $input['schedule_date'] ?? null;
$start_time = $input['start_time'] ?? null;
$end_time = $input['end_time'] ?? null;
$topic = $input['topic'] ?? null;
$location_or_link = $input['location_or_link'] ?? null;
$recording_link = $input['recording_link'] ?? null; // New field

// Basic validation: must have ID and Batch ID to identify the schedule.
if (!$id || !$batch_id) {
    echo json_encode(['success' => false, 'message' => 'Missing required identifiers (ID or Batch ID).']);
    exit();
}

try {
    // Start transaction for atomicity
    $pdo->beginTransaction();

    // 2. Fetch current schedule and batch details for validation and email content
    $stmt_fetch = $pdo->prepare("
        SELECT 
            bs.schedule_date, bs.start_time, bs.end_time, bs.topic, bs.location_or_link, bs.recording_link,
            b.batch_name, b.instructor_id, c.course_name
        FROM batch_schedules bs
        JOIN batches b ON bs.batch_id = b.id
        JOIN courses c ON b.course_id = c.id
        WHERE bs.id = ? AND bs.batch_id = ?
    ");
    $stmt_fetch->execute([$id, $batch_id]);
    $current_schedule = $stmt_fetch->fetch(PDO::FETCH_ASSOC);

    if (!$current_schedule) {
        throw new Exception('Schedule not found.');
    }

    // Check ownership for instructors before updating
    if ($_SESSION['user_role'] === 'instructor' && $current_schedule['instructor_id'] != $_SESSION['user_id']) {
        throw new Exception('You do not have permission to edit this schedule.');
    }

    // Dynamically build the UPDATE query
    $update_fields = [];
    $params = [];
    $email_details = []; // To build the email message

    if ($schedule_date !== null && $schedule_date !== $current_schedule['schedule_date']) {
        $update_fields[] = "schedule_date = ?";
        $params[] = $schedule_date;
        $email_details[] = "<li>The class date has been changed from **" . htmlspecialchars($current_schedule['schedule_date']) . "** to **" . htmlspecialchars($schedule_date) . "**</li>";
    }
    if ($start_time !== null && $start_time !== $current_schedule['start_time']) {
        $update_fields[] = "start_time = ?";
        $params[] = $start_time;
        $email_details[] = "<li>The start time has been changed from **" . date('h:i A', strtotime($current_schedule['start_time'])) . "** to **" . date('h:i A', strtotime($start_time)) . "**</li>";
    }
    if ($end_time !== null && $end_time !== $current_schedule['end_time']) {
        $update_fields[] = "end_time = ?";
        $params[] = $end_time;
        $email_details[] = "<li>The end time has been changed from **" . date('h:i A', strtotime($current_schedule['end_time'])) . "** to **" . date('h:i A', strtotime($end_time)) . "**</li>";
    }
    if ($topic !== null && $topic !== $current_schedule['topic']) {
        $update_fields[] = "topic = ?";
        $params[] = $topic;
        $email_details[] = "<li>The topic has been changed from **" . htmlspecialchars($current_schedule['topic']) . "** to **" . htmlspecialchars($topic) . "**</li>";
    }
    if ($location_or_link !== null && $location_or_link !== $current_schedule['location_or_link']) {
        $update_fields[] = "location_or_link = ?";
        $params[] = $location_or_link;
        $email_details[] = "<li>The location/link has been updated to: <a href='" . htmlspecialchars($location_or_link) . "'>" . htmlspecialchars($location_or_link) . "</a></li>";
    }
    
    // Check specifically for the recording link update
    if ($recording_link !== null && $recording_link !== $current_schedule['recording_link']) {
        $update_fields[] = "recording_link = ?";
        $params[] = $recording_link;
        $email_details[] = "<h3>🎥 New Class Recording Available!</h3><li>A new recording for the class has been uploaded. You can access it here: <a href='" . htmlspecialchars($recording_link) . "'>" . htmlspecialchars($recording_link) . "</a></li>";
    }

    if (empty($update_fields)) {
        // No changes made
        $pdo->rollBack(); // Nothing to commit
        echo json_encode(['success' => false, 'message' => 'No data provided for update or no changes detected.']);
        exit();
    }

    $sql = "UPDATE batch_schedules SET " . implode(", ", $update_fields) . " WHERE id = ? AND batch_id = ?";
    $params[] = $id;
    $params[] = $batch_id;

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    // If a row was updated, proceed with notifications and emails
    if ($stmt->rowCount()) {
        // 3. Fetch all enrolled students for notification
        $stmt_students = $pdo->prepare("
            SELECT u.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);

        // Prepare data for the email function and notification message
        $schedule_data_for_email = [
            'batch_name' => $current_schedule['batch_name'],
            'course_name' => $current_schedule['course_name'],
            'topic' => $topic ?? $current_schedule['topic'] // Use the new topic if available
        ];
        $email_message = "<ul>" . implode("", $email_details) . "</ul>";

        // Generate the message for the notifications table
        $notification_title = "Schedule Updated for '{$schedule_data_for_email['course_name']}'";
        $notification_message = "The schedule for your class, **{$schedule_data_for_email['topic']}**, has been updated. " . strip_tags(implode(" ", $email_details));
        
        // Prepare the notification insertion query
        $stmt_notify = $pdo->prepare("
            INSERT INTO notifications (user_id, type, title, message)
            VALUES (?, 'schedule', ?, ?)
        ");

        // 4. Send email and create notification for each enrolled student
        foreach ($enrolled_students as $student) {
            // Send email
            sendScheduleUpdateEmail($student, $schedule_data_for_email, $email_message);
            
            // Create database notification
            $stmt_notify->execute([$student['id'], $notification_title, $notification_message]);
        }

        $pdo->commit();
        echo json_encode(['success' => true, 'message' => 'Schedule updated successfully and students notified.']);
    } else {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => 'No changes made or schedule not found.']);
    }

} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log("Update Batch Schedule Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);

} catch (PDOException $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log("Update Batch Schedule PDO Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>