<?php
declare(strict_types=1);

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

if (($_SESSION['user_role'] ?? '') !== 'admin') {
    http_response_code(403);
    exit('Bạn không có quyền truy cập chức năng này.');
}

$pdo = getDbConnection();

$pageTitle = 'Thống kê đóng góp';
$pageSubtitle = 'Theo dõi hoạt động đóng góp nội dung của giáo viên';
$activeTeacherNav = 'teachers';

function contributionEventLabel(string $event): string
{
    return match ($event) {
        'created'     => 'Đã tạo',
        'submitted'   => 'Đã gửi duyệt',
        'returned'    => 'Bị trả lại',
        'resubmitted' => 'Gửi lại',
        'published'   => 'Đã xuất bản',
        default       => $event,
    };
}

function contributionEventClass(string $event): string
{
    return match ($event) {
        'submitted'   => 'event-submitted',
        'returned'    => 'event-returned',
        'resubmitted' => 'event-resubmitted',
        'published'   => 'event-published',
        default       => 'event-created',
    };
}

function tableHasColumn(PDO $pdo, string $table, string $column): bool
{
    static $cache = [];

    if (!isset($cache[$table])) {
        try {
            $rows = $pdo->query("SHOW COLUMNS FROM `{$table}`")->fetchAll(PDO::FETCH_ASSOC);
            $cache[$table] = array_column($rows, null, 'Field');
        } catch (Throwable $e) {
            $cache[$table] = [];
        }
    }

    return isset($cache[$table][$column]);
}

/* ---------- Filters ---------- */
$teacherFilter = max(0, (int)($_GET['teacher_id'] ?? 0));
$eventFilter = trim((string)($_GET['event_type'] ?? ''));
$dateFrom = trim((string)($_GET['date_from'] ?? ''));
$dateTo = trim((string)($_GET['date_to'] ?? ''));

$allowedEvents = ['created', 'submitted', 'returned', 'resubmitted', 'published'];
if ($eventFilter !== '' && !in_array($eventFilter, $allowedEvents, true)) {
    $eventFilter = '';
}

$teachers = $pdo->query(
    "SELECT id, full_name, username
     FROM users
     WHERE role = 'teacher'
     ORDER BY full_name ASC, id ASC"
)->fetchAll(PDO::FETCH_ASSOC);

/* ---------- Overall summary ---------- */
$summary = [
    'total' => 0,
    'created' => 0,
    'submitted' => 0,
    'returned' => 0,
    'resubmitted' => 0,
    'published' => 0,
];

try {
    $row = $pdo->query(
        "SELECT
            COUNT(*) AS total,
            SUM(event_type = 'created') AS created_count,
            SUM(event_type = 'submitted') AS submitted_count,
            SUM(event_type = 'returned') AS returned_count,
            SUM(event_type = 'resubmitted') AS resubmitted_count,
            SUM(event_type = 'published') AS published_count
         FROM content_contribution_events"
    )->fetch(PDO::FETCH_ASSOC) ?: [];

    $summary['total'] = (int)($row['total'] ?? 0);
    $summary['created'] = (int)($row['created_count'] ?? 0);
    $summary['submitted'] = (int)($row['submitted_count'] ?? 0);
    $summary['returned'] = (int)($row['returned_count'] ?? 0);
    $summary['resubmitted'] = (int)($row['resubmitted_count'] ?? 0);
    $summary['published'] = (int)($row['published_count'] ?? 0);
} catch (Throwable $e) {
    error_log('Contribution summary error: ' . $e->getMessage());
}

/* ---------- Per-teacher statistics ---------- */
$teacherStats = [];

try {
    $teacherStats = $pdo->query(
        "SELECT
            u.id AS teacher_id,
            u.full_name,
            u.username,
            COUNT(cce.id) AS total_events,
            SUM(cce.event_type = 'created') AS created_count,
            SUM(cce.event_type = 'submitted') AS submitted_count,
            SUM(cce.event_type = 'returned') AS returned_count,
            SUM(cce.event_type = 'resubmitted') AS resubmitted_count,
            SUM(cce.event_type = 'published') AS published_count,
            COUNT(DISTINCT CASE WHEN cce.event_type = 'published'
                THEN CONCAT(cce.content_type, ':', cce.content_id) END) AS published_contents,
            MAX(cce.created_at) AS last_contribution_at
         FROM users u
         LEFT JOIN content_contribution_events cce
                ON cce.teacher_id = u.id
         WHERE u.role = 'teacher'
         GROUP BY u.id, u.full_name, u.username
         ORDER BY published_contents DESC, total_events DESC, u.full_name ASC"
    )->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    error_log('Contribution teacher stats error: ' . $e->getMessage());
}

/* ---------- Recent history ---------- */
$where = [];
$params = [];

if ($teacherFilter > 0) {
    $where[] = 'cce.teacher_id = :teacher_id';
    $params['teacher_id'] = $teacherFilter;
}

if ($eventFilter !== '') {
    $where[] = 'cce.event_type = :event_type';
    $params['event_type'] = $eventFilter;
}

if ($dateFrom !== '') {
    $where[] = 'DATE(cce.created_at) >= :date_from';
    $params['date_from'] = $dateFrom;
}

if ($dateTo !== '') {
    $where[] = 'DATE(cce.created_at) <= :date_to';
    $params['date_to'] = $dateTo;
}

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

$historyRows = [];

try {
    $stmt = $pdo->prepare(
        "SELECT
            cce.id,
            cce.content_type,
            cce.content_id,
            cce.teacher_id,
            cce.event_type,
            cce.note,
            cce.created_at,
            u.full_name,
            u.username
         FROM content_contribution_events cce
         LEFT JOIN users u ON u.id = cce.teacher_id
         {$whereSql}
         ORDER BY cce.created_at DESC, cce.id DESC
         LIMIT 300"
    );
    $stmt->execute($params);
    $historyRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    error_log('Contribution history error: ' . $e->getMessage());
}

/* ---------- Lesson title map for current V3.2 workflow ---------- */
$lessonTitleMap = [];

if ($historyRows !== []) {
    $lessonIds = [];

    foreach ($historyRows as $row) {
        if (($row['content_type'] ?? '') === 'lesson') {
            $lessonIds[] = (int)$row['content_id'];
        }
    }

    $lessonIds = array_values(array_unique(array_filter($lessonIds)));

    if ($lessonIds !== []) {
        try {
            $titleColumn = tableHasColumn($pdo, 'lessons', 'title')
                ? 'title'
                : (tableHasColumn($pdo, 'lessons', 'name')
                    ? 'name'
                    : (tableHasColumn($pdo, 'lessons', 'lesson_number') ? 'lesson_number' : ''));

            if ($titleColumn !== '') {
                $placeholders = implode(',', array_fill(0, count($lessonIds), '?'));
                $stmt = $pdo->prepare(
                    "SELECT id, `{$titleColumn}` AS title
                     FROM lessons
                     WHERE id IN ({$placeholders})"
                );
                $stmt->execute($lessonIds);

                foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $lessonRow) {
                    $lessonTitleMap[(int)$lessonRow['id']] = (string)$lessonRow['title'];
                }
            }
        } catch (Throwable $e) {
            error_log('Contribution lesson title map error: ' . $e->getMessage());
        }
    }
}

ob_start();
?>

<style>
.contribution-page{display:grid;gap:20px}
.contribution-head{display:flex;align-items:flex-start;justify-content:space-between;gap:14px}
.contribution-head h1{margin:0;font-size:26px;color:#10213d}
.contribution-head p{margin:6px 0 0;color:#718096;font-size:14px}
.back-link{display:inline-flex;align-items:center;gap:6px;padding:9px 12px;border:1px solid #dbe3ee;border-radius:10px;background:#fff;color:#334155;text-decoration:none;font-size:13px;font-weight:800}
.summary-grid{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px}
.summary-card{background:#fff;border:1px solid #e6ebf2;border-radius:16px;padding:16px;box-shadow:0 5px 18px rgba(18,38,63,.04)}
.summary-card span{display:block;color:#7a8799;font-size:12px;font-weight:700}
.summary-card strong{display:block;margin-top:7px;font-size:27px;color:#15233c}
.panel{background:#fff;border:1px solid #e6ebf2;border-radius:18px;box-shadow:0 5px 18px rgba(18,38,63,.05);overflow:hidden}
.panel-head{padding:17px 20px;border-bottom:1px solid #edf1f6}
.panel-head h2{margin:0;font-size:18px;color:#15233c}
.panel-head p{margin:5px 0 0;color:#7a8799;font-size:13px}
.table-wrap{overflow:auto}
.tbl{width:100%;border-collapse:collapse;min-width:980px}
.tbl th,.tbl td{padding:12px 14px;border-bottom:1px solid #edf1f6;text-align:left;font-size:13px;vertical-align:middle}
.tbl th{background:#f8fafc;color:#617085}
.teacher-name{font-weight:800;color:#14243c}
.muted{color:#8491a4;font-size:12px}
.num{font-weight:800;color:#15233c}
.event-badge{display:inline-flex;padding:4px 8px;border-radius:999px;font-size:11px;font-weight:800;white-space:nowrap}
.event-created{background:#f1f5f9;color:#475569}
.event-submitted{background:#eef6ff;color:#1d4ed8}
.event-returned{background:#fff1f2;color:#be123c}
.event-resubmitted{background:#fff7ed;color:#c2410c}
.event-published{background:#ecfdf3;color:#166534}
.filter-bar{display:flex;align-items:end;gap:10px;flex-wrap:wrap;padding:14px 20px;border-bottom:1px solid #edf1f6;background:#f8fbff}
.filter-bar label{display:grid;gap:5px;color:#617085;font-size:12px;font-weight:700}
.filter-bar input,.filter-bar select{min-height:38px;border:1px solid #dbe3ee;border-radius:9px;padding:7px 9px;background:#fff;font:inherit}
.filter-button{min-height:38px;border:0;border-radius:9px;padding:8px 12px;background:#2563eb;color:#fff;font-weight:800;cursor:pointer}
.reset-link{display:inline-flex;align-items:center;min-height:38px;padding:7px 11px;border:1px solid #dbe3ee;border-radius:9px;background:#fff;color:#475569;text-decoration:none;font-size:12px;font-weight:800}
.note-cell{max-width:300px;white-space:normal;word-break:break-word}
.content-link{color:#1d4ed8;text-decoration:none;font-weight:800}
.empty{padding:28px 20px;text-align:center;color:#7b8899}
@media(max-width:1000px){.summary-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media(max-width:600px){.contribution-head{flex-direction:column}.summary-grid{grid-template-columns:1fr}}
</style>

<div class="contribution-page">

    <div class="contribution-head">
        <div>
            <h1>📊 Thống kê đóng góp giáo viên</h1>
            <p>Theo dõi lịch sử gửi duyệt, trả sửa, gửi lại và xuất bản nội dung.</p>
        </div>

        <a class="back-link" href="index.php">← Quản lý giáo viên</a>
    </div>

    <div class="summary-grid">
        <div class="summary-card">
            <span>Tổng sự kiện</span>
            <strong><?= $summary['total'] ?></strong>
        </div>

        <div class="summary-card">
            <span>Đã gửi duyệt</span>
            <strong><?= $summary['submitted'] ?></strong>
        </div>

        <div class="summary-card">
            <span>Bị trả lại</span>
            <strong><?= $summary['returned'] ?></strong>
        </div>

        <div class="summary-card">
            <span>Gửi lại</span>
            <strong><?= $summary['resubmitted'] ?></strong>
        </div>

        <div class="summary-card">
            <span>Đã xuất bản</span>
            <strong><?= $summary['published'] ?></strong>
        </div>
    </div>

    <section class="panel">
        <div class="panel-head">
            <h2>Đóng góp theo giáo viên</h2>
            <p>Thống kê lấy trực tiếp từ bảng content_contribution_events.</p>
        </div>

        <?php if ($teacherStats === []): ?>
            <div class="empty">Chưa có dữ liệu giáo viên.</div>
        <?php else: ?>
            <div class="table-wrap">
                <table class="tbl">
                    <thead>
                        <tr>
                            <th>Giáo viên</th>
                            <th>Submitted</th>
                            <th>Returned</th>
                            <th>Resubmitted</th>
                            <th>Published</th>
                            <th>Nội dung Published</th>
                            <th>Lần đóng góp cuối</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($teacherStats as $row): ?>
                        <tr>
                            <td>
                                <div class="teacher-name">
                                    <?= htmlspecialchars((string)$row['full_name'], ENT_QUOTES, 'UTF-8') ?>
                                </div>
                                <div class="muted">
                                    @<?= htmlspecialchars((string)$row['username'], ENT_QUOTES, 'UTF-8') ?>
                                    • ID <?= (int)$row['teacher_id'] ?>
                                </div>
                            </td>
                            <td class="num"><?= (int)$row['submitted_count'] ?></td>
                            <td class="num"><?= (int)$row['returned_count'] ?></td>
                            <td class="num"><?= (int)$row['resubmitted_count'] ?></td>
                            <td class="num"><?= (int)$row['published_count'] ?></td>
                            <td class="num"><?= (int)$row['published_contents'] ?></td>
                            <td>
                                <?= !empty($row['last_contribution_at'])
                                    ? htmlspecialchars((string)$row['last_contribution_at'], ENT_QUOTES, 'UTF-8')
                                    : '<span class="muted">Chưa có</span>' ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </section>

    <section class="panel">
        <div class="panel-head">
            <h2>Lịch sử đóng góp</h2>
            <p>Tối đa 300 sự kiện gần nhất theo bộ lọc hiện tại.</p>
        </div>

        <form method="get" class="filter-bar">
            <label>
                Giáo viên
                <select name="teacher_id">
                    <option value="">Tất cả giáo viên</option>
                    <?php foreach ($teachers as $teacher): ?>
                        <option
                            value="<?= (int)$teacher['id'] ?>"
                            <?= $teacherFilter === (int)$teacher['id'] ? 'selected' : '' ?>
                        >
                            <?= htmlspecialchars((string)$teacher['full_name'], ENT_QUOTES, 'UTF-8') ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </label>

            <label>
                Sự kiện
                <select name="event_type">
                    <option value="">Tất cả sự kiện</option>
                    <?php foreach ($allowedEvents as $event): ?>
                        <option value="<?= htmlspecialchars($event, ENT_QUOTES, 'UTF-8') ?>"
                            <?= $eventFilter === $event ? 'selected' : '' ?>>
                            <?= htmlspecialchars(contributionEventLabel($event), ENT_QUOTES, 'UTF-8') ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </label>

            <label>
                Từ ngày
                <input type="date" name="date_from" value="<?= htmlspecialchars($dateFrom, ENT_QUOTES, 'UTF-8') ?>">
            </label>

            <label>
                Đến ngày
                <input type="date" name="date_to" value="<?= htmlspecialchars($dateTo, ENT_QUOTES, 'UTF-8') ?>">
            </label>

            <button class="filter-button" type="submit">Lọc</button>
            <a class="reset-link" href="contributions.php">Xóa lọc</a>
        </form>

        <?php if ($historyRows === []): ?>
            <div class="empty">Chưa có lịch sử đóng góp phù hợp.</div>
        <?php else: ?>
            <div class="table-wrap">
                <table class="tbl">
                    <thead>
                        <tr>
                            <th>Thời gian</th>
                            <th>Giáo viên</th>
                            <th>Nội dung</th>
                            <th>Sự kiện</th>
                            <th>Ghi chú</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($historyRows as $row): ?>
                        <?php
                            $contentType = (string)($row['content_type'] ?? '');
                            $contentId = (int)($row['content_id'] ?? 0);
                            $contentLabel = ucfirst($contentType) . ' #' . $contentId;
                            $contentHref = '';

                            if ($contentType === 'lesson') {
                                $title = trim((string)($lessonTitleMap[$contentId] ?? ''));
                                if ($title !== '') {
                                    $contentLabel = $title . ' • Lesson #' . $contentId;
                                }
                                $contentHref = '../lessons/detail.php?id=' . $contentId;
                            }
                        ?>
                        <tr>
                            <td><?= htmlspecialchars((string)$row['created_at'], ENT_QUOTES, 'UTF-8') ?></td>
                            <td>
                                <div class="teacher-name">
                                    <?= htmlspecialchars((string)($row['full_name'] ?? 'Teacher #' . (int)$row['teacher_id']), ENT_QUOTES, 'UTF-8') ?>
                                </div>
                                <div class="muted">
                                    <?= !empty($row['username'])
                                        ? '@' . htmlspecialchars((string)$row['username'], ENT_QUOTES, 'UTF-8')
                                        : 'ID ' . (int)$row['teacher_id'] ?>
                                </div>
                            </td>
                            <td>
                                <?php if ($contentHref !== ''): ?>
                                    <a class="content-link" href="<?= htmlspecialchars($contentHref, ENT_QUOTES, 'UTF-8') ?>">
                                        <?= htmlspecialchars($contentLabel, ENT_QUOTES, 'UTF-8') ?>
                                    </a>
                                <?php else: ?>
                                    <?= htmlspecialchars($contentLabel, ENT_QUOTES, 'UTF-8') ?>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="event-badge <?= contributionEventClass((string)$row['event_type']) ?>">
                                    <?= htmlspecialchars(contributionEventLabel((string)$row['event_type']), ENT_QUOTES, 'UTF-8') ?>
                                </span>
                            </td>
                            <td class="note-cell">
                                <?= !empty($row['note'])
                                    ? nl2br(htmlspecialchars((string)$row['note'], ENT_QUOTES, 'UTF-8'))
                                    : '<span class="muted">—</span>' ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </section>
</div>

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