<?php
declare(strict_types=1);

/**
 * EnglishSpeak - Teacher Units
 * File: teacher/units/delete.php
 *
 * GET  -> show confirmation
 * POST -> delete an empty Unit safely
 */

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

$pdo = getDbConnection();

function removeUnitThumbnail(?string $relativePath): void
{
    if ($relativePath === null || $relativePath === '') {
        return;
    }

    $normalized = str_replace('\\', '/', ltrim($relativePath, '/'));

    if (!str_starts_with($normalized, 'uploads/units/')) {
        return;
    }

    $absolutePath = dirname(__DIR__, 2)
        . DIRECTORY_SEPARATOR
        . str_replace('/', DIRECTORY_SEPARATOR, $normalized);

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

/* =========================================================
   POST: delete Unit
   ========================================================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $unitId = max(0, (int)($_POST['id'] ?? 0));

    if ($unitId <= 0) {
        $_SESSION['units_message'] = 'Invalid Unit ID.';
        $_SESSION['units_message_type'] = 'error';
        header('Location: index.php');
        exit;
    }

    try {
        $pdo->beginTransaction();

        $unitStmt = $pdo->prepare(
            "SELECT id, book_id, thumbnail
             FROM units
             WHERE id = ?
             LIMIT 1
             FOR UPDATE"
        );
        $unitStmt->execute([$unitId]);
        $unit = $unitStmt->fetch(PDO::FETCH_ASSOC);

        if (!$unit) {
            $pdo->rollBack();

            $_SESSION['units_message'] = 'Unit not found.';
            $_SESSION['units_message_type'] = 'error';
            header('Location: index.php');
            exit;
        }

        $bookId = (int)$unit['book_id'];

        $lessonStmt = $pdo->prepare(
            "SELECT COUNT(*)
             FROM lessons
             WHERE unit_id = ?"
        );
        $lessonStmt->execute([$unitId]);
        $lessonCount = (int)$lessonStmt->fetchColumn();

        $practiceStmt = $pdo->prepare(
            "SELECT COUNT(*)
             FROM activities a
             INNER JOIN lessons l ON l.id = a.lesson_id
             WHERE l.unit_id = ?"
        );
        $practiceStmt->execute([$unitId]);
        $practiceCount = (int)$practiceStmt->fetchColumn();

        if ($lessonCount > 0 || $practiceCount > 0) {
            $pdo->rollBack();

            $_SESSION['units_message'] =
                'This Unit cannot be deleted because it still contains Lessons or Practices.';
            $_SESSION['units_message_type'] = 'error';

            header('Location: delete.php?id=' . $unitId);
            exit;
        }

        $deleteStmt = $pdo->prepare(
            "DELETE FROM units
             WHERE id = ?
             LIMIT 1"
        );
        $deleteStmt->execute([$unitId]);

        if ($deleteStmt->rowCount() !== 1) {
            throw new RuntimeException('The Unit was not deleted.');
        }

        $pdo->commit();

        removeUnitThumbnail((string)($unit['thumbnail'] ?? ''));

        $_SESSION['units_message'] = 'Unit deleted successfully.';
        $_SESSION['units_message_type'] = 'success';

        header('Location: index.php?book_id=' . $bookId);
        exit;
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        $_SESSION['units_message'] =
            'Could not delete the Unit. Please try again.';
        $_SESSION['units_message_type'] = 'error';

        header('Location: delete.php?id=' . $unitId);
        exit;
    }
}

/* =========================================================
   GET: show confirmation
   ========================================================= */
$unitId = max(0, (int)($_GET['id'] ?? 0));

if ($unitId <= 0) {
    $_SESSION['units_message'] = 'Invalid Unit ID.';
    $_SESSION['units_message_type'] = 'error';
    header('Location: index.php');
    exit;
}

$stmt = $pdo->prepare(
    "SELECT
        u.id,
        u.book_id,
        u.unit_number,
        u.title,
        u.thumbnail,
        u.description,
        u.status,
        b.name AS book_name,
        (
            SELECT COUNT(*)
            FROM lessons l
            WHERE l.unit_id = u.id
        ) AS lesson_count,
        (
            SELECT COUNT(*)
            FROM lessons l2
            INNER JOIN activities a ON a.lesson_id = l2.id
            WHERE l2.unit_id = u.id
        ) AS practice_count
     FROM units u
     INNER JOIN books b ON b.id = u.book_id
     WHERE u.id = ?
     LIMIT 1"
);
$stmt->execute([$unitId]);
$unit = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$unit) {
    $_SESSION['units_message'] = 'Unit not found.';
    $_SESSION['units_message_type'] = 'error';
    header('Location: index.php');
    exit;
}

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

$lessonCount = (int)$unit['lesson_count'];
$practiceCount = (int)$unit['practice_count'];
$canDelete = $lessonCount === 0 && $practiceCount === 0;

ob_start();
?>

<style>
.unit-delete-page{display:grid;gap:18px;max-width:860px}
.unit-delete-header{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}
.unit-delete-header h2{margin:4px 0 0;font-size:28px;line-height:1.2}
.unit-delete-kicker{display:block;color:#dc2626;font-size:12px;font-weight:800;letter-spacing:.09em;text-transform:uppercase}
.unit-delete-card{padding:22px;border:1px solid #e5e7eb;border-radius:18px;background:#fff}
.unit-delete-summary{display:flex;align-items:center;gap:14px;padding:16px;border:1px solid #e5e7eb;border-radius:14px;background:#f8fafc}
.unit-delete-badge{display:grid;place-items:center;flex:0 0 56px;height:56px;border-radius:15px;background:#fee2e2;color:#b91c1c;font-weight:850}
.unit-delete-summary strong{display:block;color:#0f172a;font-size:17px}
.unit-delete-summary small{display:block;margin-top:4px;color:#64748b}
.unit-delete-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin-top:16px}
.unit-delete-stat{padding:14px;border:1px solid #e5e7eb;border-radius:13px;background:#fff}
.unit-delete-stat span{display:block;color:#64748b;font-size:12px;font-weight:700;text-transform:uppercase}
.unit-delete-stat strong{display:block;margin-top:5px;color:#0f172a;font-size:22px}
.unit-delete-warning{margin-top:18px;padding:14px 16px;border-radius:13px;line-height:1.55}
.unit-delete-warning-danger{border:1px solid #fecaca;background:#fef2f2;color:#991b1b}
.unit-delete-warning-safe{border:1px solid #fde68a;background:#fffbeb;color:#92400e}
.unit-delete-actions{display:flex;justify-content:flex-end;gap:10px;margin-top:20px;padding-top:18px;border-top:1px solid #eef2f7}
.unit-delete-button{
    display:inline-flex;align-items:center;justify-content:center;min-height:42px;
    padding:0 16px;border:0;border-radius:10px;background:#dc2626;color:#fff;
    font:inherit;font-weight:750;cursor:pointer
}
.unit-delete-button:hover{background:#b91c1c}
.unit-delete-button:disabled{cursor:not-allowed;opacity:.45}
@media(max-width:680px){
    .unit-delete-header{flex-direction:column;align-items:stretch}
    .unit-delete-grid{grid-template-columns:1fr}
    .unit-delete-actions{flex-direction:column-reverse}
    .unit-delete-actions .button,.unit-delete-button{width:100%}
}
</style>

<div class="unit-delete-page">
    <div class="unit-delete-header">
        <div>
            <span class="unit-delete-kicker">Danger Zone</span>
            <h2>Delete Unit</h2>
            <p style="margin:7px 0 0;color:#64748b">
                Review this Unit carefully before deleting it.
            </p>
        </div>

        <a href="index.php?book_id=<?= (int)$unit['book_id'] ?>" class="button button-secondary">
            ← Back to Units
        </a>
    </div>

    <div class="unit-delete-card">
        <div class="unit-delete-summary">
            <div class="unit-delete-badge">
                <?php
                $numberText = (string)$unit['unit_number'];
                preg_match('/\d+/', $numberText, $numberMatch);
                echo htmlspecialchars(isset($numberMatch[0]) ? 'U' . $numberMatch[0] : 'UNIT', ENT_QUOTES, 'UTF-8');
                ?>
            </div>

            <div>
                <strong>
                    <?= htmlspecialchars(
                        trim((string)$unit['unit_number'] . ' • ' . (string)$unit['title']),
                        ENT_QUOTES,
                        'UTF-8'
                    ) ?>
                </strong>
                <small>
                    <?= htmlspecialchars((string)$unit['book_name'], ENT_QUOTES, 'UTF-8') ?>
                    · <?= (string)$unit['status'] === 'active' ? 'Active' : 'Hidden' ?>
                </small>
            </div>
        </div>

        <div class="unit-delete-grid">
            <div class="unit-delete-stat">
                <span>Lessons</span>
                <strong><?= $lessonCount ?></strong>
            </div>

            <div class="unit-delete-stat">
                <span>Practices</span>
                <strong><?= $practiceCount ?></strong>
            </div>

            <div class="unit-delete-stat">
                <span>Book</span>
                <strong style="font-size:15px">
                    <?= htmlspecialchars((string)$unit['book_name'], ENT_QUOTES, 'UTF-8') ?>
                </strong>
            </div>
        </div>

        <?php if ($canDelete): ?>
            <div class="unit-delete-warning unit-delete-warning-safe">
                This Unit has no Lessons or Practices. It can be deleted safely.
                This action cannot be undone.
            </div>
        <?php else: ?>
            <div class="unit-delete-warning unit-delete-warning-danger">
                <strong>This Unit cannot be deleted yet.</strong><br>
                It still contains <?= $lessonCount ?> Lesson(s) and <?= $practiceCount ?> Practice(s).
                Remove or move those Lessons first to protect learning content and student progress.
            </div>
        <?php endif; ?>

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

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

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