<?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 = 'Referral';
$pageSubtitle = 'Theo dõi nguồn học sinh do giáo viên tạo/import';
$activeTeacherNav = 'teachers';

$selectedTeacherId = max(0, (int)($_GET['teacher_id'] ?? 0));

$summary = [
    'teacher_codes' => 0,
    'referred_students' => 0,
    'teachers_with_students' => 0,
];

try {
    $summary['teacher_codes'] = (int)$pdo->query(
        "SELECT COUNT(*) FROM teacher_referral_codes WHERE status = 'active'"
    )->fetchColumn();
    $summary['referred_students'] = (int)$pdo->query(
        "SELECT COUNT(*) FROM student_referrals"
    )->fetchColumn();
    $summary['teachers_with_students'] = (int)$pdo->query(
        "SELECT COUNT(DISTINCT teacher_id) FROM student_referrals"
    )->fetchColumn();
} catch (Throwable $e) {
    // Giữ trang hoạt động nếu DB referral chưa sẵn sàng.
}

$teachers = [];
try {
    $teachers = $pdo->query(
        "SELECT
            u.id AS teacher_id,
            u.full_name,
            u.username,
            u.email,
            u.status AS teacher_status,
            tp.province,
            tp.school_name,
            trc.referral_code,
            trc.status AS referral_status,
            COUNT(sr.id) AS referred_count,
            MAX(sr.referred_at) AS last_referred_at
         FROM users u
         LEFT JOIN teacher_profiles tp ON tp.user_id = u.id
         LEFT JOIN teacher_referral_codes trc ON trc.teacher_id = u.id
         LEFT JOIN student_referrals sr ON sr.teacher_id = u.id
         WHERE u.role = 'teacher'
         GROUP BY
            u.id, u.full_name, u.username, u.email, u.status,
            tp.province, tp.school_name,
            trc.referral_code, trc.status
         ORDER BY referred_count DESC, u.full_name ASC, u.id ASC"
    )->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $teachers = [];
}

$selectedTeacher = null;
$studentRows = [];
if ($selectedTeacherId > 0) {
    try {
        $stmt = $pdo->prepare(
            "SELECT
                u.id AS teacher_id,
                u.full_name,
                u.username,
                tp.province,
                tp.school_name,
                trc.referral_code
             FROM users u
             LEFT JOIN teacher_profiles tp ON tp.user_id = u.id
             LEFT JOIN teacher_referral_codes trc ON trc.teacher_id = u.id
             WHERE u.id = :teacher_id AND u.role = 'teacher'
             LIMIT 1"
        );
        $stmt->execute(['teacher_id' => $selectedTeacherId]);
        $selectedTeacher = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;

        if ($selectedTeacher) {
            $studentStmt = $pdo->prepare(
                "SELECT
                    sr.id AS referral_id,
                    sr.student_id,
                    sr.referral_code_used,
                    sr.referred_at,
                    s.full_name,
                    s.phone,
                    s.email,
                    s.grade,
                    s.class_name,
                    s.status AS student_status
                 FROM student_referrals sr
                 INNER JOIN students s ON s.id = sr.student_id
                 WHERE sr.teacher_id = :teacher_id
                 ORDER BY sr.referred_at DESC, sr.id DESC"
            );
            $studentStmt->execute(['teacher_id' => $selectedTeacherId]);
            $studentRows = $studentStmt->fetchAll(PDO::FETCH_ASSOC);
        }
    } catch (Throwable $e) {
        $selectedTeacher = null;
        $studentRows = [];
    }
}

function esReferralDate(?string $value): string
{
    $value = trim((string)$value);
    if ($value === '') return '—';
    $ts = strtotime($value);
    return $ts ? date('d/m/Y H:i', $ts) : $value;
}

function esReferralText($value): string
{
    $value = trim((string)$value);
    return $value !== '' ? $value : '—';
}

ob_start();
?>
<style>
.referral-page{display:grid;gap:20px}
.referral-head{display:flex;justify-content:space-between;align-items:flex-start;gap:14px;flex-wrap:wrap}
.referral-head h1{margin:0;font-size:26px;color:#10213d}
.referral-head p{margin:6px 0 0;color:#718096;font-size:14px}
.referral-actions{display:flex;gap:10px;flex-wrap:wrap}
.referral-back{display:inline-flex;align-items:center;gap:7px;padding:9px 13px;border-radius:10px;background:#fff;border:1px solid #dce4ef;color:#274060;text-decoration:none;font-weight:700}
.referral-cards{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}
.referral-card{background:#fff;border:1px solid #e4eaf2;border-radius:16px;padding:18px;box-shadow:0 5px 18px rgba(18,38,63,.05)}
.referral-card span{display:block;color:#77859a;font-size:13px;font-weight:700;margin-bottom:8px}
.referral-card strong{font-size:30px;color:#10213d}
.panel{background:#fff;border:1px solid #e4eaf2;border-radius:18px;overflow:hidden;box-shadow:0 5px 18px rgba(18,38,63,.05)}
.panel-head{padding:17px 20px;border-bottom:1px solid #edf1f6;display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap}
.panel-head h2{margin:0;font-size:18px;color:#10213d}
.panel-head p{margin:5px 0 0;color:#7a8798;font-size:13px}
.table-wrap{overflow:auto;max-height:62vh}
.referral-table{width:100%;border-collapse:collapse;min-width:1050px}
.referral-table th,.referral-table td{padding:12px 14px;border-bottom:1px solid #edf1f6;text-align:left;vertical-align:middle;font-size:13px}
.referral-table th{position:sticky;top:0;z-index:3;background:#f7f9fc;color:#526176;font-size:12px;text-transform:uppercase;letter-spacing:.02em}
.referral-table tbody tr:hover{background:#fbfdff}
.code-pill{display:inline-flex;padding:5px 9px;border-radius:999px;background:#eaf9ef;color:#126b37;font-weight:800;letter-spacing:.03em}
.count-pill{display:inline-flex;min-width:30px;justify-content:center;padding:5px 8px;border-radius:999px;background:#eef4ff;color:#2459c4;font-weight:800}
.status{display:inline-flex;padding:4px 8px;border-radius:999px;font-size:12px;font-weight:800}
.status-active{background:#eaf9ef;color:#126b37}.status-other{background:#f3f4f6;color:#667085}
.view-link{display:inline-flex;padding:7px 10px;border-radius:9px;background:#2563eb;color:#fff;text-decoration:none;font-weight:700;white-space:nowrap}
.empty{padding:28px;text-align:center;color:#7c899b}
.detail-summary{display:flex;gap:8px;flex-wrap:wrap;color:#667085;font-size:13px}
.detail-summary b{color:#10213d}
@media(max-width:900px){.referral-cards{grid-template-columns:1fr}.referral-head{flex-direction:column}}
</style>

<div class="referral-page">
    <div class="referral-head">
        <div>
            <h1>🎯 Referral học sinh</h1>
            <p>Referral chỉ ghi nhận học sinh do giáo viên tạo/import. Học sinh tự đăng ký không có referral.</p>
        </div>
        <div class="referral-actions">
            <a class="referral-back" href="./">← Quản lý giáo viên</a>
        </div>
    </div>

    <div class="referral-cards">
        <div class="referral-card">
            <span>Giáo viên có mã active</span>
            <strong><?= (int)$summary['teacher_codes'] ?></strong>
        </div>
        <div class="referral-card">
            <span>Học sinh có referral</span>
            <strong><?= (int)$summary['referred_students'] ?></strong>
        </div>
        <div class="referral-card">
            <span>Giáo viên đã có học sinh referral</span>
            <strong><?= (int)$summary['teachers_with_students'] ?></strong>
        </div>
    </div>

    <section class="panel">
        <div class="panel-head">
            <div>
                <h2>Thống kê theo giáo viên</h2>
                <p>Mã referral và số học sinh được ghi nhận cho từng giáo viên.</p>
            </div>
        </div>
        <?php if (!$teachers): ?>
            <div class="empty">Chưa có dữ liệu giáo viên/referral.</div>
        <?php else: ?>
            <div class="table-wrap">
                <table class="referral-table">
                    <thead>
                    <tr>
                        <th>Giáo viên</th>
                        <th>Tỉnh</th>
                        <th>Trường</th>
                        <th>Mã referral</th>
                        <th>Trạng thái</th>
                        <th>Học sinh</th>
                        <th>Lần gần nhất</th>
                        <th></th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($teachers as $teacher): ?>
                        <?php $tid = (int)($teacher['teacher_id'] ?? 0); ?>
                        <tr>
                            <td>
                                <strong><?= htmlspecialchars(esReferralText($teacher['full_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></strong><br>
                                <small style="color:#7a8798"><?= htmlspecialchars(esReferralText($teacher['username'] ?? $teacher['email'] ?? ''), ENT_QUOTES, 'UTF-8') ?></small>
                            </td>
                            <td><?= htmlspecialchars(esReferralText($teacher['province'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                            <td><?= htmlspecialchars(esReferralText($teacher['school_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                            <td>
                                <?php if (trim((string)($teacher['referral_code'] ?? '')) !== ''): ?>
                                    <span class="code-pill"><?= htmlspecialchars((string)$teacher['referral_code'], ENT_QUOTES, 'UTF-8') ?></span>
                                <?php else: ?>—<?php endif; ?>
                            </td>
                            <td>
                                <?php $active = (($teacher['teacher_status'] ?? '') === 'active'); ?>
                                <span class="status <?= $active ? 'status-active' : 'status-other' ?>"><?= $active ? 'Active' : htmlspecialchars(esReferralText($teacher['teacher_status'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>
                            </td>
                            <td><span class="count-pill"><?= (int)($teacher['referred_count'] ?? 0) ?></span></td>
                            <td><?= htmlspecialchars(esReferralDate($teacher['last_referred_at'] ?? null), ENT_QUOTES, 'UTF-8') ?></td>
                            <td><a class="view-link" href="?teacher_id=<?= $tid ?>#student-detail">Xem học sinh</a></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </section>

    <?php if ($selectedTeacher): ?>
        <section class="panel" id="student-detail">
            <div class="panel-head">
                <div>
                    <h2>Học sinh referral — <?= htmlspecialchars(esReferralText($selectedTeacher['full_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></h2>
                    <p class="detail-summary">
                        <span>Mã: <b><?= htmlspecialchars(esReferralText($selectedTeacher['referral_code'] ?? ''), ENT_QUOTES, 'UTF-8') ?></b></span>
                        <span>•</span>
                        <span>Tổng: <b><?= count($studentRows) ?> học sinh</b></span>
                        <span>•</span>
                        <span><?= htmlspecialchars(esReferralText($selectedTeacher['school_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>
                    </p>
                </div>
                <a class="referral-back" href="referral-report.php">Đóng chi tiết</a>
            </div>
            <?php if (!$studentRows): ?>
                <div class="empty">Giáo viên này chưa có học sinh referral.</div>
            <?php else: ?>
                <div class="table-wrap">
                    <table class="referral-table">
                        <thead>
                        <tr>
                            <th>ID</th>
                            <th>Học sinh</th>
                            <th>SĐT / Email</th>
                            <th>Khối</th>
                            <th>Lớp</th>
                            <th>Mã đã ghi nhận</th>
                            <th>Ngày ghi nhận</th>
                            <th>Trạng thái</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($studentRows as $student): ?>
                            <tr>
                                <td><?= (int)($student['student_id'] ?? 0) ?></td>
                                <td><strong><?= htmlspecialchars(esReferralText($student['full_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></strong></td>
                                <td>
                                    <?= htmlspecialchars(esReferralText($student['phone'] ?? ''), ENT_QUOTES, 'UTF-8') ?><br>
                                    <small style="color:#7a8798"><?= htmlspecialchars(esReferralText($student['email'] ?? ''), ENT_QUOTES, 'UTF-8') ?></small>
                                </td>
                                <td><?= htmlspecialchars(esReferralText($student['grade'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                                <td><?= htmlspecialchars(esReferralText($student['class_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                                <td><span class="code-pill"><?= htmlspecialchars(esReferralText($student['referral_code_used'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span></td>
                                <td><?= htmlspecialchars(esReferralDate($student['referred_at'] ?? null), ENT_QUOTES, 'UTF-8') ?></td>
                                <td><?= htmlspecialchars(esReferralText($student['student_status'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </section>
    <?php endif; ?>
</div>

<?php
$content = ob_get_clean();
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="theme-color" content="#2563eb">
    <title><?= htmlspecialchars($pageTitle . ' | EnglishSpeak', ENT_QUOTES, 'UTF-8') ?></title>
    <link rel="stylesheet" href="../assets/css/app.css?v=1.1">
    <link rel="stylesheet" href="../assets/css/sidebar.css?v=1.1">
    <link rel="stylesheet" href="../assets/css/topbar.css?v=1.1">
    <link rel="stylesheet" href="../assets/css/cards.css?v=1.1">
    <link rel="stylesheet" href="../assets/css/buttons.css?v=1.1">
    <link rel="stylesheet" href="../assets/css/forms.css?v=1.1">
    <link rel="stylesheet" href="../assets/css/tables.css?v=1.1">
    <link rel="stylesheet" href="../assets/css/utilities.css?v=1.1">
</head>
<body>
<div class="app-shell">
    <?php require __DIR__ . '/../partials/sidebar.php'; ?>
    <div class="sidebar-overlay" id="sidebarOverlay" aria-hidden="true"></div>
    <main class="main-area">
        <?php require __DIR__ . '/../partials/topbar.php'; ?>
        <section class="page-content"><?= $content ?></section>
        <?php require __DIR__ . '/../partials/footer.php'; ?>
    </main>
</div>
<script src="../assets/js/app.js?v=1.1"></script>
</body>
</html>
