<?php
declare(strict_types=1);

/**
 * EnglishSpeak - Teacher Units
 * File: teacher/units/index.php
 *
 * Architecture:
 * Books -> Units -> Lessons -> Practices
 */

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

$pdo = getDbConnection();

$pageTitle = 'Units';
$pageSubtitle = 'Manage units inside each book';
$activeTeacherNav = 'content';

$keyword = trim((string)($_GET['keyword'] ?? ''));
$bookId = max(0, (int)($_GET['book_id'] ?? 0));
$status = (string)($_GET['status'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 12;

if (!in_array($status, ['', 'active', 'inactive'], true)) {
    $status = '';
}

/**
 * Build a URL while preserving current filters.
 *
 * @param array<string, int|string|null> $changes
 */
function unitsUrl(array $changes = []): string
{
    $query = [
        'keyword' => trim((string)($_GET['keyword'] ?? '')),
        'book_id' => max(0, (int)($_GET['book_id'] ?? 0)),
        'status' => (string)($_GET['status'] ?? ''),
        'page' => max(1, (int)($_GET['page'] ?? 1)),
    ];

    foreach ($changes as $key => $value) {
        if ($value === null || $value === '' || $value === 0) {
            unset($query[$key]);
        } else {
            $query[$key] = $value;
        }
    }

    return 'index.php' . ($query !== [] ? '?' . http_build_query($query) : '');
}

/**
 * Short visual label, for example "Unit 12" -> "U12".
 */
function unitShortLabel(string $unitNumber): string
{
    if (preg_match('/\d+/', $unitNumber, $match) === 1) {
        return 'U' . $match[0];
    }

    $text = trim($unitNumber);
    return $text !== '' ? mb_strtoupper(mb_substr($text, 0, 4)) : 'UNIT';
}

// Books for filter.
$booksStmt = $pdo->query(
    "SELECT id, name
     FROM books
     WHERE status = 'active'
     ORDER BY sort_order ASC, name ASC"
);
$books = $booksStmt->fetchAll(PDO::FETCH_ASSOC);

// Current book label.
$selectedBookName = '';
foreach ($books as $book) {
    if ((int)$book['id'] === $bookId) {
        $selectedBookName = (string)$book['name'];
        break;
    }
}

// Dynamic WHERE.
$where = [];
$params = [];

if ($keyword !== '') {
    $where[] = '(u.unit_number LIKE :keyword OR u.title LIKE :keyword OR u.description LIKE :keyword)';
    $params[':keyword'] = '%' . $keyword . '%';
}

if ($bookId > 0) {
    $where[] = 'u.book_id = :book_id';
    $params[':book_id'] = $bookId;
}

if ($status !== '') {
    $where[] = 'u.status = :status';
    $params[':status'] = $status;
}

$whereSql = $where !== [] ? 'WHERE ' . implode(' AND ', $where) : '';

// Count.
$countStmt = $pdo->prepare(
    "SELECT COUNT(*)
     FROM units u
     {$whereSql}"
);
$countStmt->execute($params);
$totalUnits = (int)$countStmt->fetchColumn();

$totalPages = max(1, (int)ceil($totalUnits / $perPage));
if ($page > $totalPages) {
    $page = $totalPages;
}
$offset = ($page - 1) * $perPage;

// Unit list.
$listSql = "
    SELECT
        u.id,
        u.book_id,
        u.unit_number,
        u.title,
        u.thumbnail,
        u.description,
        u.required_xp,
        u.sort_order,
        u.status,
        u.created_at,
        u.updated_at,
        b.name AS book_name,
        (
            SELECT COUNT(*)
            FROM lessons l
            WHERE l.unit_id = u.id
              AND l.status = 'active'
        ) AS lesson_count,
        (
            SELECT COUNT(*)
            FROM lessons l2
            INNER JOIN activities a
                ON a.lesson_id = l2.id
               AND a.status = 'active'
            WHERE l2.unit_id = u.id
              AND l2.status = 'active'
        ) AS practice_count
    FROM units u
    INNER JOIN books b ON b.id = u.book_id
    {$whereSql}
    ORDER BY b.sort_order ASC, b.name ASC, u.sort_order ASC, u.id ASC
    LIMIT :limit OFFSET :offset
";

$listStmt = $pdo->prepare($listSql);
foreach ($params as $name => $value) {
    $listStmt->bindValue($name, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR);
}
$listStmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
$listStmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$listStmt->execute();
$units = $listStmt->fetchAll(PDO::FETCH_ASSOC);

// Summary.
$summary = $pdo->query(
    "SELECT
        COUNT(*) AS total_count,
        SUM(status = 'active') AS active_count,
        SUM(status = 'inactive') AS inactive_count
     FROM units"
)->fetch(PDO::FETCH_ASSOC) ?: [];

$totalAll = (int)($summary['total_count'] ?? 0);
$activeAll = (int)($summary['active_count'] ?? 0);
$inactiveAll = (int)($summary['inactive_count'] ?? 0);

$message = (string)($_SESSION['units_message'] ?? '');
$messageType = (string)($_SESSION['units_message_type'] ?? 'success');
unset($_SESSION['units_message'], $_SESSION['units_message_type']);

ob_start();
?>

<style>
.units-page{display:grid;gap:18px}
.units-header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px}
.units-header h2{margin:4px 0 0;font-size:28px;line-height:1.2}
.units-kicker{display:block;color:#2563eb;font-size:12px;font-weight:800;letter-spacing:.09em;text-transform:uppercase}
.units-stats{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}
.units-stat{padding:16px 18px;border:1px solid #e5e7eb;border-radius:16px;background:#fff}
.units-stat span{display:block;color:#64748b;font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:.04em}
.units-stat strong{display:block;margin-top:6px;font-size:25px;color:#0f172a}
.units-toolbar{display:grid;grid-template-columns:minmax(220px,1fr) minmax(180px,260px) minmax(150px,200px) auto;gap:10px;padding:14px;border:1px solid #e5e7eb;border-radius:16px;background:#fff}
.units-input,.units-select{width:100%;min-height:42px;padding:0 12px;border:1px solid #dbe2ea;border-radius:10px;background:#fff;color:#0f172a;font:inherit}
.units-input:focus,.units-select:focus{outline:3px solid rgba(37,99,235,.12);border-color:#2563eb}
.units-card{overflow:hidden;border:1px solid #e5e7eb;border-radius:18px;background:#fff}
.units-table{width:100%;border-collapse:collapse}
.units-table th{padding:12px 14px;background:#f8fafc;color:#64748b;font-size:11px;text-align:left;text-transform:uppercase;letter-spacing:.04em;border-bottom:1px solid #e5e7eb}
.units-table td{padding:14px;border-bottom:1px solid #eef2f7;vertical-align:middle}
.units-table tr:last-child td{border-bottom:0}
.units-table tbody tr:hover{background:#fbfdff}
.unit-cell{display:flex;align-items:center;gap:12px;min-width:260px}
.unit-badge{display:grid;place-items:center;flex:0 0 46px;height:46px;border-radius:13px;background:#eaf2ff;color:#2563eb;font-weight:800}
.unit-info strong{display:block;color:#0f172a}
.unit-info small{display:block;margin-top:4px;max-width:430px;color:#64748b;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.unit-book{font-weight:650;color:#334155}
.units-number{font-weight:750;color:#0f172a}
.units-muted{color:#64748b}
.status-pill{display:inline-flex;align-items:center;gap:6px;padding:6px 10px;border-radius:999px;font-size:12px;font-weight:750}
.status-pill:before{content:"";width:7px;height:7px;border-radius:50%}
.status-active{background:#ecfdf3;color:#15803d}.status-active:before{background:#22c55e}
.status-inactive{background:#f1f5f9;color:#64748b}.status-inactive:before{background:#94a3b8}
.units-actions{display:flex;align-items:center;gap:7px;white-space:nowrap}
.units-action{display:inline-flex;align-items:center;justify-content:center;min-height:34px;padding:0 11px;border:1px solid #dbe2ea;border-radius:9px;background:#fff;color:#334155;text-decoration:none;font-size:12px;font-weight:700}
.units-action:hover{border-color:#2563eb;color:#2563eb}
.units-action-danger:hover{border-color:#ef4444;color:#dc2626}
.units-empty{padding:58px 20px;text-align:center}
.units-empty-icon{font-size:42px}
.units-empty h3{margin:12px 0 6px}
.units-empty p{margin:0 0 18px;color:#64748b}
.units-footer{display:flex;align-items:center;justify-content:space-between;gap:16px}
.units-pagination{display:flex;align-items:center;gap:6px}
.units-pagination a,.units-pagination span{display:grid;place-items:center;min-width:36px;height:36px;padding:0 9px;border:1px solid #dbe2ea;border-radius:9px;background:#fff;color:#334155;text-decoration:none;font-size:13px;font-weight:700}
.units-pagination .current{border-color:#2563eb;background:#2563eb;color:#fff}
.units-pagination .disabled{opacity:.45}
.units-flash{padding:12px 15px;border-radius:12px;font-weight:650}
.units-flash-success{background:#ecfdf3;color:#166534;border:1px solid #bbf7d0}
.units-flash-error{background:#fef2f2;color:#991b1b;border:1px solid #fecaca}
@media(max-width:1000px){
 .units-toolbar{grid-template-columns:1fr 1fr}
 .units-stats{grid-template-columns:repeat(3,1fr)}
 .units-card{overflow-x:auto}
}
@media(max-width:680px){
 .units-header,.units-footer{align-items:stretch;flex-direction:column}
 .units-stats{grid-template-columns:1fr}
 .units-toolbar{grid-template-columns:1fr}
}
</style>

<div class="units-page">
    <div class="units-header">
        <div>
            <span class="units-kicker">Content Library</span>
            <h2>Units</h2>
            <p class="units-muted" style="margin:7px 0 0">
                Books → Units → Lessons → Practices
            </p>
        </div>

        <a href="create.php<?= $bookId > 0 ? '?book_id=' . $bookId : '' ?>" class="button button-primary">
            + Add Unit
        </a>
    </div>

    <?php if ($message !== ''): ?>
        <div class="units-flash units-flash-<?= $messageType === 'error' ? 'error' : 'success' ?>">
            <?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?>
        </div>
    <?php endif; ?>

    <div class="units-stats">
        <div class="units-stat">
            <span>Total Units</span>
            <strong><?= $totalAll ?></strong>
        </div>
        <div class="units-stat">
            <span>Active</span>
            <strong><?= $activeAll ?></strong>
        </div>
        <div class="units-stat">
            <span>Hidden</span>
            <strong><?= $inactiveAll ?></strong>
        </div>
    </div>

    <form class="units-toolbar" method="get" action="index.php">
        <input
            class="units-input"
            type="search"
            name="keyword"
            value="<?= htmlspecialchars($keyword, ENT_QUOTES, 'UTF-8') ?>"
            placeholder="Search Unit number, title..."
        >

        <select class="units-select" name="book_id" onchange="this.form.submit()">
            <option value="">All Books</option>
            <?php foreach ($books as $book): ?>
                <option value="<?= (int)$book['id'] ?>" <?= (int)$book['id'] === $bookId ? 'selected' : '' ?>>
                    <?= htmlspecialchars((string)$book['name'], ENT_QUOTES, 'UTF-8') ?>
                </option>
            <?php endforeach; ?>
        </select>

        <select class="units-select" name="status">
            <option value="">All Status</option>
            <option value="active" <?= $status === 'active' ? 'selected' : '' ?>>Active</option>
            <option value="inactive" <?= $status === 'inactive' ? 'selected' : '' ?>>Hidden</option>
        </select>

        <div style="display:flex;gap:8px">
            <button type="submit" class="button button-primary">Search</button>
            <?php if ($keyword !== '' || $bookId > 0 || $status !== ''): ?>
                <a href="index.php" class="button button-secondary">Reset</a>
            <?php endif; ?>
        </div>
    </form>

    <div class="units-card">
        <?php if ($units === []): ?>
            <div class="units-empty">
                <div class="units-empty-icon">📂</div>
                <h3>No Units found</h3>
                <p>
                    <?= $selectedBookName !== ''
                        ? 'Create the first Unit for ' . htmlspecialchars($selectedBookName, ENT_QUOTES, 'UTF-8') . '.'
                        : 'Create a Unit or adjust the current filters.' ?>
                </p>
                <a href="create.php<?= $bookId > 0 ? '?book_id=' . $bookId : '' ?>" class="button button-primary">
                    + Create Unit
                </a>
            </div>
        <?php else: ?>
            <table class="units-table">
                <thead>
                    <tr>
                        <th>Unit</th>
                        <th>Book</th>
                        <th>Lessons</th>
                        <th>Practices</th>
                        <th>Required XP</th>
                        <th>Status</th>
                        <th style="width:210px">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($units as $unit): ?>
                        <tr>
                            <td>
                                <div class="unit-cell">
                                    <div class="unit-badge">
                                        <?= htmlspecialchars(unitShortLabel((string)$unit['unit_number']), ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                    <div class="unit-info">
                                        <strong>
                                            <?= htmlspecialchars(
                                                trim((string)$unit['unit_number'] . ' • ' . (string)$unit['title']),
                                                ENT_QUOTES,
                                                'UTF-8'
                                            ) ?>
                                        </strong>
                                        <small>
                                            <?= htmlspecialchars(
                                                (string)($unit['description'] ?: 'No description'),
                                                ENT_QUOTES,
                                                'UTF-8'
                                            ) ?>
                                        </small>
                                    </div>
                                </div>
                            </td>
                            <td class="unit-book">
                                <?= htmlspecialchars((string)$unit['book_name'], ENT_QUOTES, 'UTF-8') ?>
                            </td>
                            <td class="units-number"><?= (int)$unit['lesson_count'] ?></td>
                            <td class="units-number"><?= (int)$unit['practice_count'] ?></td>
                            <td class="units-number"><?= (int)$unit['required_xp'] ?></td>
                            <td>
                                <?php $isActive = (string)$unit['status'] === 'active'; ?>
                                <span class="status-pill <?= $isActive ? 'status-active' : 'status-inactive' ?>">
                                    <?= $isActive ? 'Active' : 'Hidden' ?>
                                </span>
                            </td>
                            <td>
                                <div class="units-actions">
                                    <a class="units-action" href="../lessons/?unit_id=<?= (int)$unit['id'] ?>">
                                        Lessons
                                    </a>
                                    <a class="units-action" href="edit.php?id=<?= (int)$unit['id'] ?>">
                                        Edit
                                    </a>
                                    <a
                                        class="units-action units-action-danger"
                                        href="delete.php?id=<?= (int)$unit['id'] ?>"
                                    >
                                        Delete
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

    <div class="units-footer">
        <div class="units-muted">
            Showing
            <strong><?= $totalUnits === 0 ? 0 : $offset + 1 ?></strong>
            –
            <strong><?= min($offset + $perPage, $totalUnits) ?></strong>
            of <strong><?= $totalUnits ?></strong> Unit(s)
        </div>

        <?php if ($totalPages > 1): ?>
            <nav class="units-pagination" aria-label="Units pagination">
                <?php if ($page > 1): ?>
                    <a href="<?= htmlspecialchars(unitsUrl(['page' => $page - 1]), ENT_QUOTES, 'UTF-8') ?>">‹</a>
                <?php else: ?>
                    <span class="disabled">‹</span>
                <?php endif; ?>

                <?php
                $startPage = max(1, $page - 2);
                $endPage = min($totalPages, $page + 2);
                for ($i = $startPage; $i <= $endPage; $i++):
                ?>
                    <?php if ($i === $page): ?>
                        <span class="current"><?= $i ?></span>
                    <?php else: ?>
                        <a href="<?= htmlspecialchars(unitsUrl(['page' => $i]), ENT_QUOTES, 'UTF-8') ?>">
                            <?= $i ?>
                        </a>
                    <?php endif; ?>
                <?php endfor; ?>

                <?php if ($page < $totalPages): ?>
                    <a href="<?= htmlspecialchars(unitsUrl(['page' => $page + 1]), ENT_QUOTES, 'UTF-8') ?>">›</a>
                <?php else: ?>
                    <span class="disabled">›</span>
                <?php endif; ?>
            </nav>
        <?php endif; ?>
    </div>
</div>

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