<?php
declare(strict_types=1);

/**
 * EnglishSpeak - Lesson Activities
 * File: teacher/lesson-activities/delete.php
 *
 * GET  -> show delete confirmation
 * POST -> permanently delete an Activity only when no dependent data exists
 */

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

$pdo = getDbConnection();

/**
 * Returns tables that reference activities.id through foreign keys.
 *
 * @return array<int, array{table_name:string,column_name:string}>
 */
function activityReferencingTables(PDO $pdo): array
{
    $stmt = $pdo->prepare(
        "SELECT
            TABLE_NAME AS table_name,
            COLUMN_NAME AS column_name
         FROM information_schema.KEY_COLUMN_USAGE
         WHERE REFERENCED_TABLE_SCHEMA = DATABASE()
           AND REFERENCED_TABLE_NAME = 'activities'
           AND REFERENCED_COLUMN_NAME = 'id'
         ORDER BY TABLE_NAME, COLUMN_NAME"
    );
    $stmt->execute();

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

/**
 * Counts dependent records safely.
 *
 * @return array<int, array{table_name:string,column_name:string,row_count:int}>
 */
function activityDependencyCounts(PDO $pdo, int $activityId): array
{
    $dependencies = [];

    foreach (activityReferencingTables($pdo) as $relation) {
        $table = (string)$relation['table_name'];
        $column = (string)$relation['column_name'];

        // information_schema supplies identifiers, but validate again before interpolation.
        if (
            preg_match('/^[A-Za-z0-9_]+$/', $table) !== 1
            || preg_match('/^[A-Za-z0-9_]+$/', $column) !== 1
        ) {
            continue;
        }

        $stmt = $pdo->prepare(
            "SELECT COUNT(*)
             FROM `{$table}`
             WHERE `{$column}` = ?"
        );
        $stmt->execute([$activityId]);

        $count = (int)$stmt->fetchColumn();

        if ($count > 0) {
            $dependencies[] = [
                'table_name' => $table,
                'column_name' => $column,
                'row_count' => $count,
            ];
        }
    }

    return $dependencies;
}

/**
 * Converts a database table name into a readable label.
 */
function dependencyLabel(string $tableName): string
{
    $labels = [
        'activity_words' => 'linked words',
        'student_activity_progress' => 'student progress records',
        'student_progress' => 'student progress records',
        'activity_attempts' => 'student attempts',
        'game_results' => 'game results',
        'student_game_results' => 'game results',
        'assignments' => 'assignments',
    ];

    return $labels[$tableName]
        ?? ucwords(str_replace('_', ' ', $tableName));
}

/**
 * Reads one Activity with its Lesson path.
 *
 * @return array<string,mixed>|false
 */
function findActivityForDelete(PDO $pdo, int $activityId): array|false
{
    $columns = $pdo->query("SHOW COLUMNS FROM activities")->fetchAll(PDO::FETCH_ASSOC);
    $columnNames = array_column($columns, 'Field');

    $titleColumn = in_array('title', $columnNames, true)
        ? 'a.title'
        : (in_array('name', $columnNames, true) ? 'a.name' : "'Activity'");

    $typeColumn = in_array('activity_type', $columnNames, true)
        ? 'a.activity_type'
        : (in_array('type', $columnNames, true) ? 'a.type' : "'activity'");

    $statusColumn = in_array('status', $columnNames, true)
        ? 'a.status'
        : "'active'";

    $stmt = $pdo->prepare(
        "SELECT
            a.id,
            a.lesson_id,
            {$titleColumn} AS activity_title,
            {$typeColumn} AS activity_type,
            {$statusColumn} AS activity_status,
            l.lesson_number,
            l.title AS lesson_title,
            u.id AS unit_id,
            u.unit_number,
            u.title AS unit_title,
            b.id AS book_id,
            b.name AS book_name
         FROM activities a
         INNER JOIN lessons l ON l.id = a.lesson_id
         INNER JOIN units u ON u.id = l.unit_id
         INNER JOIN books b ON b.id = u.book_id
         WHERE a.id = ?
         LIMIT 1"
    );
    $stmt->execute([$activityId]);

    return $stmt->fetch(PDO::FETCH_ASSOC);
}

function activityDeleteTypeLabel(string $type): string
{
    return match ($type) {
        'flashcards' => 'Flashcards',
        'listen_repeat', 'pronunciation' => 'Listen & Repeat',
        'speaking' => 'Speaking',
        'memory' => 'Memory',
        'matching' => 'Matching',
        'quiz' => 'Quiz',
        'typing' => 'Typing',
        'word_search' => 'Word Search',
        'sentence_builder' => 'Sentence Builder',
        'vocabulary' => 'Word List',
        default => ucwords(str_replace(['_', '-'], ' ', $type !== '' ? $type : 'Activity')),
    };
}

function activityDeleteIcon(string $type): string
{
    return match ($type) {
        'flashcards' => '🃏',
        'listen_repeat', 'pronunciation' => '🔊',
        'speaking' => '🎤',
        'memory' => '🧠',
        'matching' => '🧩',
        'quiz' => '🎯',
        'typing' => '⌨️',
        'word_search' => '🔎',
        'sentence_builder' => '🧱',
        'vocabulary' => '🔤',
        default => '🎮',
    };
}

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

    if ($activityId <= 0) {
        $_SESSION['activities_message'] = 'Invalid Activity ID.';
        $_SESSION['activities_message_type'] = 'error';
        header('Location: ../lessons/index.php');
        exit;
    }

    try {
        $pdo->beginTransaction();

        $activityStmt = $pdo->prepare(
            "SELECT id, lesson_id
             FROM activities
             WHERE id = ?
             LIMIT 1
             FOR UPDATE"
        );
        $activityStmt->execute([$activityId]);
        $activity = $activityStmt->fetch(PDO::FETCH_ASSOC);

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

            $_SESSION['activities_message'] = 'Activity not found.';
            $_SESSION['activities_message_type'] = 'error';
            header('Location: ../lessons/index.php');
            exit;
        }

        $lessonId = (int)$activity['lesson_id'];
        $dependencies = activityDependencyCounts($pdo, $activityId);

        if ($dependencies !== []) {
            $pdo->rollBack();

            $_SESSION['activities_message'] =
                'This Activity cannot be deleted because it still has linked learning or student data.';
            $_SESSION['activities_message_type'] = 'error';

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

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

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

        $pdo->commit();

        $_SESSION['activities_message'] = 'Activity deleted successfully.';
        $_SESSION['activities_message_type'] = 'success';

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

        $_SESSION['activities_message'] =
            'Could not delete the Activity. Please try again.';
        $_SESSION['activities_message_type'] = 'error';

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

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

if ($activityId <= 0) {
    $_SESSION['activities_message'] = 'Invalid Activity ID.';
    $_SESSION['activities_message_type'] = 'error';
    header('Location: ../lessons/index.php');
    exit;
}

$activity = findActivityForDelete($pdo, $activityId);

if (!$activity) {
    $_SESSION['activities_message'] = 'Activity not found.';
    $_SESSION['activities_message_type'] = 'error';
    header('Location: ../lessons/index.php');
    exit;
}

$dependencies = activityDependencyCounts($pdo, $activityId);
$canDelete = $dependencies === [];

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

ob_start();
?>

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

<div class="activity-delete-page">
    <div class="activity-delete-head">
        <div>
            <span class="activity-delete-kicker">Danger Zone</span>
            <h2>Delete Activity</h2>
            <p class="activity-delete-path">
                <?= htmlspecialchars((string)$activity['book_name'], ENT_QUOTES, 'UTF-8') ?>
                → <?= htmlspecialchars(
                    (string)$activity['unit_number'] . ' • ' . (string)$activity['unit_title'],
                    ENT_QUOTES,
                    'UTF-8'
                ) ?>
                → <strong><?= htmlspecialchars(
                    (string)$activity['lesson_number'] . ' • ' . (string)$activity['lesson_title'],
                    ENT_QUOTES,
                    'UTF-8'
                ) ?></strong>
            </p>
        </div>

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

    <div class="activity-delete-card">
        <div class="activity-delete-summary">
            <div class="activity-delete-icon">
                <?= activityDeleteIcon((string)$activity['activity_type']) ?>
            </div>

            <div>
                <strong>
                    <?= htmlspecialchars((string)$activity['activity_title'], ENT_QUOTES, 'UTF-8') ?>
                </strong>
                <small>
                    <?= htmlspecialchars(
                        activityDeleteTypeLabel((string)$activity['activity_type']),
                        ENT_QUOTES,
                        'UTF-8'
                    ) ?>
                    · <?= (string)$activity['activity_status'] === 'inactive' ? 'Hidden' : 'Active' ?>
                </small>
            </div>
        </div>

        <div class="activity-delete-grid">
            <div class="activity-delete-stat">
                <span>Book</span>
                <strong><?= htmlspecialchars((string)$activity['book_name'], ENT_QUOTES, 'UTF-8') ?></strong>
            </div>

            <div class="activity-delete-stat">
                <span>Unit</span>
                <strong><?= htmlspecialchars(
                    (string)$activity['unit_number'] . ' • ' . (string)$activity['unit_title'],
                    ENT_QUOTES,
                    'UTF-8'
                ) ?></strong>
            </div>

            <div class="activity-delete-stat">
                <span>Lesson</span>
                <strong><?= htmlspecialchars(
                    (string)$activity['lesson_number'] . ' • ' . (string)$activity['lesson_title'],
                    ENT_QUOTES,
                    'UTF-8'
                ) ?></strong>
            </div>
        </div>

        <?php if ($canDelete): ?>
            <div class="activity-delete-warning activity-delete-safe">
                This Activity has no linked learning data or student records.
                It can be deleted safely. This action cannot be undone.
            </div>
        <?php else: ?>
            <div class="activity-delete-warning activity-delete-blocked">
                <strong>This Activity cannot be deleted yet.</strong><br>
                It still has related data:

                <ul class="activity-delete-dependencies">
                    <?php foreach ($dependencies as $dependency): ?>
                        <li>
                            <?= (int)$dependency['row_count'] ?>
                            <?= htmlspecialchars(
                                dependencyLabel((string)$dependency['table_name']),
                                ENT_QUOTES,
                                'UTF-8'
                            ) ?>
                        </li>
                    <?php endforeach; ?>
                </ul>

                Remove or detach those records first. Hiding the Activity is safer when students
                have already practiced it.
            </div>
        <?php endif; ?>

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

            <form action="delete.php" method="post" style="margin:0">
                <input type="hidden" name="id" value="<?= $activityId ?>">

                <button
                    type="submit"
                    class="activity-delete-button"
                    <?= $canDelete ? '' : 'disabled' ?>
                    onclick="return confirm('Delete this Activity permanently?');"
                >
                    Delete Activity
                </button>
            </form>
        </div>
    </div>
</div>

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