<?php
declare(strict_types=1);

/**
 * EnglishSpeak - Teacher Lessons
 * File: teacher/lessons/delete.php
 *
 * Safe Lesson deletion with ownership protection.
 */

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

$pdo = getDbConnection();

$teacherId = (int)($_SESSION['user_id'] ?? 0);
$role = strtolower((string)($_SESSION['user_role'] ?? 'teacher'));
$isAdmin = ($role === 'admin');

$lessonId = max(
    0,
    (int)(($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST'
        ? ($_POST['id'] ?? 0)
        : ($_GET['id'] ?? 0))
);

if ($lessonId <= 0) {
    $_SESSION['lessons_message'] = 'Invalid Lesson ID.';
    $_SESSION['lessons_message_type'] = 'error';
    header('Location: index.php');
    exit;
}

$stmt = $pdo->prepare(
    "SELECT
        l.id,
        l.unit_id,
        l.created_by_teacher_id,
        l.lesson_number,
        l.title,
        l.thumbnail,
        l.status,
        u.book_id,
        u.unit_number,
        u.title AS unit_title,
        b.name AS book_name,
        (SELECT COUNT(*) FROM activities a WHERE a.lesson_id = l.id) AS activity_count,
        (
            SELECT COUNT(*)
            FROM student_content_progress scp
            WHERE scp.content_type = 'lesson'
              AND scp.content_id = l.id
        ) AS lesson_progress_count,
        (
            SELECT COUNT(*)
            FROM xp_transactions xt
            WHERE xt.lesson_id = l.id
        ) AS xp_count,
        (
            SELECT COUNT(*)
            FROM student_activity_attempts saa
            WHERE saa.lesson_id = l.id
        ) AS attempt_count
     FROM lessons l
     INNER JOIN units u ON u.id = l.unit_id
     INNER JOIN books b ON b.id = u.book_id
     WHERE l.id = ?
     LIMIT 1"
);
$stmt->execute([$lessonId]);
$lesson = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$lesson) {
    $_SESSION['lessons_message'] = 'Lesson not found.';
    $_SESSION['lessons_message_type'] = 'error';
    header('Location: index.php');
    exit;
}

$lessonOwnerId = (int)($lesson['created_by_teacher_id'] ?? 0);
$canManageLesson = $isAdmin || ($lessonOwnerId > 0 && $lessonOwnerId === $teacherId);

if (!$canManageLesson) {
    $_SESSION['lessons_message'] = 'You do not have permission to delete this Lesson.';
    $_SESSION['lessons_message_type'] = 'error';
    header('Location: index.php?book_id=' . (int)$lesson['book_id'] . '&unit_id=' . (int)$lesson['unit_id']);
    exit;
}

if (!$isAdmin) {
    $bookAccessStmt = $pdo->prepare(
        "SELECT 1
         FROM teacher_books
         WHERE teacher_id = ?
           AND book_id = ?
         LIMIT 1"
    );
    $bookAccessStmt->execute([$teacherId, (int)$lesson['book_id']]);

    if (!$bookAccessStmt->fetchColumn()) {
        $_SESSION['lessons_message'] = 'You are not allowed to manage Lessons in this Book.';
        $_SESSION['lessons_message_type'] = 'error';
        header('Location: index.php');
        exit;
    }
}

$activityCount = (int)$lesson['activity_count'];
$lessonProgressCount = (int)$lesson['lesson_progress_count'];
$xpCount = (int)$lesson['xp_count'];
$attemptCount = (int)$lesson['attempt_count'];

$canDelete = $activityCount === 0
    && $lessonProgressCount === 0
    && $xpCount === 0
    && $attemptCount === 0;

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    if (!$canDelete) {
        $_SESSION['lessons_message'] =
            'Cannot delete this Lesson because it still has Activities or student learning history.';
        $_SESSION['lessons_message_type'] = 'error';
        header('Location: delete.php?id=' . $lessonId);
        exit;
    }

    try {
        $pdo->beginTransaction();

        $delete = $pdo->prepare('DELETE FROM lessons WHERE id = ?');
        $delete->execute([$lessonId]);

        if ($delete->rowCount() !== 1) {
            throw new RuntimeException('Lesson could not be deleted.');
        }

        $pdo->commit();

        if (!empty($lesson['thumbnail'])) {
            $thumbnailPath = dirname(__DIR__, 2)
                . DIRECTORY_SEPARATOR
                . str_replace('/', DIRECTORY_SEPARATOR, (string)$lesson['thumbnail']);

            if (is_file($thumbnailPath)) {
                @unlink($thumbnailPath);
            }
        }

        $_SESSION['lessons_message'] = 'Lesson deleted successfully.';
        $_SESSION['lessons_message_type'] = 'success';
        header(
            'Location: index.php?book_id=' . (int)$lesson['book_id']
            . '&unit_id=' . (int)$lesson['unit_id']
        );
        exit;
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        error_log('EnglishSpeak Lesson delete error: ' . $e->getMessage());
        $_SESSION['lessons_message'] = 'Could not delete the Lesson.';
        $_SESSION['lessons_message_type'] = 'error';
        header('Location: delete.php?id=' . $lessonId);
        exit;
    }
}

$pageTitle = 'Delete Lesson';
$pageSubtitle = 'Confirm before deleting this Lesson';
$activeTeacherNav = 'content';

ob_start();
?>
<style>
.lesson-delete-page{display:grid;gap:18px;max-width:860px}
.lesson-delete-header{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}
.lesson-delete-card{padding:22px;border:1px solid #e5e7eb;border-radius:18px;background:#fff}
.lesson-delete-summary{padding:16px;border:1px solid #e5e7eb;border-radius:14px;background:#f8fafc}
.lesson-delete-summary strong{display:block;color:#0f172a;font-size:18px}
.lesson-delete-summary small{display:block;margin-top:5px;color:#64748b}
.lesson-delete-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin-top:16px}
.lesson-delete-stat{padding:14px;border:1px solid #e5e7eb;border-radius:13px;background:#fff}
.lesson-delete-stat span{display:block;color:#64748b;font-size:11px;font-weight:700;text-transform:uppercase}
.lesson-delete-stat strong{display:block;margin-top:5px;color:#0f172a;font-size:22px}
.lesson-delete-warning{margin-top:18px;padding:14px 16px;border-radius:13px;line-height:1.55}
.lesson-delete-warning-danger{border:1px solid #fecaca;background:#fef2f2;color:#991b1b}
.lesson-delete-warning-safe{border:1px solid #fde68a;background:#fffbeb;color:#92400e}
.lesson-delete-actions{display:flex;justify-content:flex-end;gap:10px;margin-top:20px;padding-top:18px;border-top:1px solid #eef2f7}
.lesson-delete-button{min-height:42px;padding:0 16px;border:0;border-radius:10px;background:#dc2626;color:#fff;font:inherit;font-weight:750;cursor:pointer}
.lesson-delete-button:disabled{cursor:not-allowed;opacity:.45}
@media(max-width:680px){
    .lesson-delete-header{flex-direction:column}
    .lesson-delete-grid{grid-template-columns:1fr 1fr}
    .lesson-delete-actions{flex-direction:column-reverse}
}
</style>

<div class="lesson-delete-page">
    <div class="lesson-delete-header">
        <div>
            <div style="color:#dc2626;font-size:12px;font-weight:800;text-transform:uppercase">Danger Zone</div>
            <h2 style="margin:5px 0 0">Delete Lesson</h2>
            <p style="margin:7px 0 0;color:#64748b">Review this Lesson before deleting it.</p>
        </div>

        <a
            class="button button-secondary"
            href="index.php?book_id=<?= (int)$lesson['book_id'] ?>&amp;unit_id=<?= (int)$lesson['unit_id'] ?>"
        >
            ← Back to Lessons
        </a>
    </div>

    <div class="lesson-delete-card">
        <div class="lesson-delete-summary">
            <strong>
                <?= htmlspecialchars(
                    trim((string)$lesson['lesson_number'] . ' • ' . (string)$lesson['title']),
                    ENT_QUOTES,
                    'UTF-8'
                ) ?>
            </strong>
            <small>
                <?= htmlspecialchars((string)$lesson['book_name'], ENT_QUOTES, 'UTF-8') ?>
                → <?= htmlspecialchars(
                    trim((string)$lesson['unit_number'] . ' • ' . (string)$lesson['unit_title']),
                    ENT_QUOTES,
                    'UTF-8'
                ) ?>
            </small>
        </div>

        <div class="lesson-delete-grid">
            <div class="lesson-delete-stat"><span>Activities</span><strong><?= $activityCount ?></strong></div>
            <div class="lesson-delete-stat"><span>Lesson Progress</span><strong><?= $lessonProgressCount ?></strong></div>
            <div class="lesson-delete-stat"><span>XP Rows</span><strong><?= $xpCount ?></strong></div>
            <div class="lesson-delete-stat"><span>Attempts</span><strong><?= $attemptCount ?></strong></div>
        </div>

        <?php if ($canDelete): ?>
            <div class="lesson-delete-warning lesson-delete-warning-safe">
                This Lesson has no Activities or student learning history. It can be deleted safely.
            </div>
        <?php else: ?>
            <div class="lesson-delete-warning lesson-delete-warning-danger">
                <strong>This Lesson cannot be deleted.</strong><br>
                Hide it instead, or remove only unused content. Student progress and XP references are protected.
            </div>
        <?php endif; ?>

        <div class="lesson-delete-actions">
            <a
                class="button button-secondary"
                href="index.php?book_id=<?= (int)$lesson['book_id'] ?>&amp;unit_id=<?= (int)$lesson['unit_id'] ?>"
            >
                Cancel
            </a>

            <form method="post" style="margin:0">
                <input type="hidden" name="id" value="<?= $lessonId ?>">
                <button
                    type="submit"
                    class="lesson-delete-button"
                    <?= $canDelete ? '' : 'disabled' ?>
                    onclick="return confirm('Delete this Lesson permanently?');"
                >
                    Delete Lesson
                </button>
            </form>
        </div>
    </div>
</div>

<?php
$content = ob_get_clean();
require __DIR__ . '/../layouts/app.php';
