<?php
declare(strict_types=1);

require __DIR__ . '/partials/auth.php';
require_once __DIR__ . '/../config/database.php';

$pdo = getDbConnection();

$currentUserId = (int)($_SESSION['user_id'] ?? 0);
$currentRole = strtolower(trim((string)($_SESSION['user_role'] ?? $_SESSION['role'] ?? 'teacher')));
$bookId = filter_input(INPUT_POST, 'book_id', FILTER_VALIDATE_INT);
$returnUrl = trim((string)($_POST['return_url'] ?? '/EnglishSpeak/teacher/dashboard/'));

if (!$bookId) {
    header('Location: /EnglishSpeak/teacher/dashboard/');
    exit;
}

/*
 * Prevent open redirects. Only allow returning to Teacher Portal.
 */
if (
    $returnUrl === ''
    || !str_starts_with($returnUrl, '/EnglishSpeak/teacher/')
    || str_starts_with($returnUrl, '//')
) {
    $returnUrl = '/EnglishSpeak/teacher/dashboard/';
}

if ($currentRole === 'admin') {
    $stmt = $pdo->prepare(
        "SELECT id
         FROM books
         WHERE id = ?
           AND status = 'active'
         LIMIT 1"
    );
    $stmt->execute([$bookId]);
} else {
    $stmt = $pdo->prepare(
        "SELECT b.id
         FROM teacher_content_assignments tca
         INNER JOIN books b ON b.id = tca.book_id
         WHERE tca.teacher_id = ?
           AND tca.book_id = ?
           AND tca.status = 'active'
           AND b.status = 'active'
         LIMIT 1"
    );
    $stmt->execute([$currentUserId, $bookId]);
}

if ($stmt->fetchColumn()) {
    $_SESSION['teacher_book_id'] = (int)$bookId;
    $_SESSION['teacher_book_changed'] = 1;
}

header('Location: ' . $returnUrl);
exit;
