<?php
require_once __DIR__ . '/config/database.php';

// search.php - Trang tra cứu kết quả tuyển sinh từ Google Sheets
session_start();
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" type="image/png" href="<?php echo BASE_URL; ?>/assets/logo.png">
    <title>Tra cứu kết quả tuyển sinh - ĐH Hạ Long</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="<?php echo BASE_URL; ?>/assets/css/public.css">
    <style>
        .search-hero {
            background: #f7f9fc;
            padding: 48px 0 32px;
        }
        .search-box {
            max-width: 560px;
            margin: 0 auto;
            position: relative;
            z-index: 2;
        }
        .search-box .form-control {
            height: 52px;
            border: none;
            border-radius: 12px 0 0 12px;
            font-size: 1rem;
            padding-left: 44px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.15);
        }
        .search-box .input-icon {
            position: absolute;
            left: 14px;
            top: 50%;
            transform: translateY(-50%);
            color: #94a3b8;
            z-index: 5;
            font-size: 1.1rem;
        }
        .search-box .btn-search {
            height: 52px;
            border-radius: 0 12px 12px 0;
            padding: 0 24px;
            font-weight: 600;
            background: #f59e0b;
            border: none;
            color: #fff;
            white-space: nowrap;
            transition: background .2s;
        }
        .search-box .btn-search:hover { background: #d97706; }

        /* Result cards */
        .result-card {
            background: #fff;
            border-radius: 12px;
            border: 1px solid #e2e8f0;
            overflow: hidden;
            transition: transform .2s, box-shadow .2s;
        }
        .result-card:hover { transform: translateY(-2px); box-shadow: 0 8px 24px rgba(0,0,0,0.08); }
        .result-card .card-top {
            background: #1A3A6E;
            padding: 14px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .result-card .card-top .nv-label { color: #fff; font-weight: 700; font-size: .9rem; }
        .result-card .card-top .badge-status {
            font-size: .75rem;
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
        }
        .info-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 0;
        }
        .info-cell {
            padding: 10px 20px;
            border-bottom: 1px solid #f1f5f9;
        }
        .info-cell:nth-child(odd) { border-right: 1px solid #f1f5f9; }
        .info-cell .label { font-size: .75rem; color: #94a3b8; text-transform: uppercase; letter-spacing: .3px; margin-bottom: 2px; }
        .info-cell .value { font-size: .9rem; font-weight: 600; color: #1e293b; }
        .info-cell .value.highlight { color: #dc2626; font-size: 1.05rem; }
        .info-cell .value.major { color: #1A3A6E; }
        .download-bar {
            padding: 14px 20px;
            background: linear-gradient(135deg, #ecfdf5, #d1fae5);
            border-top: 2px solid #10b981;
            text-align: center;
        }
        .download-bar a {
            display: inline-block;
            padding: 8px 24px;
            font-size: .88rem;
            font-weight: 700;
            text-decoration: none;
            color: #fff;
            background: linear-gradient(135deg, #10b981, #059669);
            border-radius: 8px;
            transition: transform .2s, box-shadow .2s;
        }
        .download-bar a:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(16,185,129,0.4); color: #fff; }

        @media (max-width: 575px) {
            .info-grid { grid-template-columns: 1fr; }
            .info-cell:nth-child(odd) { border-right: none; }
            .search-hero { padding: 32px 0 44px; }
            
            .result-card .row.g-2 { --bs-gutter-x: 0.35rem; --bs-gutter-y: 0.35rem; }
            .result-card .px-3 { padding-left: 0.4rem !important; padding-right: 0.4rem !important; }
            .result-card .py-2 { padding-top: 0.3rem !important; padding-bottom: 0.3rem !important; }
            .result-card .gap-3 { gap: 0.35rem !important; }
            .result-card .gap-2 { gap: 0.25rem !important; }
            .result-card span.fw-bold { font-size: 0.65rem !important; letter-spacing: 0; }
            .result-card div.text-dark { font-size: 0.85rem !important; letter-spacing: 0; }
            .result-card div.fs-5 { font-size: 1.05rem !important; }
            .result-card div.fs-6 { font-size: 0.85rem !important; }
            .result-card .me-2.text-center { width: 12px !important; font-size: 0.75rem !important; margin-right: 0.3rem !important; }
        }

        /* Custom Brand Colors for Right Column */
        .bg-hl-navy { background-color: rgba(26, 58, 110, 0.08) !important; }
        .border-hl-navy { border-color: rgba(26, 58, 110, 0.25) !important; }
        .text-hl-navy { color: #1A3A6E !important; }

        .bg-hl-orange { background-color: rgba(245, 158, 11, 0.1) !important; }
        .border-hl-orange { border-color: rgba(245, 158, 11, 0.3) !important; }
        .text-hl-orange { color: #d97706 !important; }
    </style>
</head>
<body style="background: #f7f9fc;">

<?php include __DIR__ . '/includes/header.php'; ?>

<!-- Hero Search -->
<div class="search-hero">
    <div class="container text-center">
        <h1 class="fw-bold mb-2" style="font-size: 1.6rem; color: #1A3A6E;">
            <i class="bi bi-search me-2"></i>Tra cứu kết quả xét tuyển
        </h1>
        <p class="text-muted mb-4" style="font-size: .9rem;">Nhập số CCCD/CMND để tra cứu kết quả tuyển sinh ĐH Hạ Long 2026</p>
        <form id="searchForm" onsubmit="handleSearch(event)">
            <div class="search-box d-flex">
                <div class="position-relative flex-grow-1">
                    <i class="bi bi-person-vcard input-icon"></i>
                    <input type="text" class="form-control" id="cccdInput" placeholder="Nhập số CCCD/CMND…" required pattern="[0-9]{9,12}" title="Nhập từ 9-12 chữ số" autocomplete="off" inputmode="numeric">
                </div>
                <button class="btn btn-search" type="submit" id="btnSearch">
                    <i class="bi bi-search me-1"></i> Tra cứu
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Results Area -->
<div class="container-xl">
    <div id="loadingIndicator" class="text-center py-4 d-none" aria-live="polite">
        <div class="spinner-border text-primary" role="status" style="width: 1.5rem; height: 1.5rem;"></div>
        <span class="ms-2 text-muted small">Đang tra cứu dữ liệu…</span>
    </div>
    <div id="alertError" class="alert alert-danger border-0 shadow-sm d-none" role="alert" aria-live="polite">
        <i class="bi bi-exclamation-triangle-fill me-2" aria-hidden="true"></i><span id="errorMsg"></span>
    </div>
    <div id="resultsContainer" aria-live="polite"></div>
</div>

<div class="pb-5"></div>

<?php include __DIR__ . '/includes/footer.php'; ?>

<script>
function handleSearch(e) {
    e.preventDefault();
    const cccd = document.getElementById('cccdInput').value.trim();
    if (!cccd) return;

    document.getElementById('resultsContainer').innerHTML = '';
    document.getElementById('alertError').classList.add('d-none');
    document.getElementById('loadingIndicator').classList.remove('d-none');
    document.getElementById('btnSearch').disabled = true;

    fetch(`api_search_sheets.php?cccd=${encodeURIComponent(cccd)}`)
        .then(r => r.json())
        .then(data => {
            document.getElementById('loadingIndicator').classList.add('d-none');
            document.getElementById('btnSearch').disabled = false;
            if (data.status === 'success' && Array.isArray(data.data) && data.data.length > 0) {
                showResults(data.data);
            } else {
                showError(data.message || 'Không tìm thấy kết quả cho số CCCD này.');
            }
        })
        .catch(() => {
            document.getElementById('loadingIndicator').classList.add('d-none');
            document.getElementById('btnSearch').disabled = false;
            showError('Lỗi kết nối máy chủ. Vui lòng thử lại.');
        });
}

function showError(msg) {
    document.getElementById('errorMsg').innerText = msg;
    document.getElementById('alertError').classList.remove('d-none');
}

function showResults(items) {
    const c = document.getElementById('resultsContainer');
    let html = `<p class="text-muted small mb-3 text-center"><i class="bi bi-check-circle text-success me-1"></i>Tìm thấy <strong>${items.length}</strong> nguyện vọng</p>`;

    // === Responsive Cards Layout ===
    html += `<div class="row row-cols-1 g-3 mx-auto" style="max-width: 800px;">`;
    items.forEach((item, i) => {
        const st = item['Trạng thái hồ sơ trên cổng bộ GD&ĐT'] || '';
        let badgeHtml = '';
        if (st) {
            let bc = 'bg-warning text-dark';
            if (/trúng|hợp lệ/i.test(st)) bc = 'bg-success text-white';
            else if (/trượt|từ chối/i.test(st)) bc = 'bg-danger text-white';
            badgeHtml = `<span class="badge-status ${bc}">${st}</span>`;
        }

        const maHoSoKey = Object.keys(item).find(k => k.toLowerCase() === 'mã hồ sơ');
        const maHoSo = maHoSoKey ? item[maHoSoKey] : '';
        const hsBadge = maHoSo ? `<span class="badge bg-white text-primary px-2 py-1 me-2 shadow-sm" style="font-size: 0.75rem;"><i class="bi bi-upc-scan me-1"></i>${maHoSo}</span>` : '';

        const titleText = '';
        const link = item['Link Giấy Báo Nhập Học'];
        const dlBar = (link && link.trim())
            ? `<div class="download-bar mt-auto"><a href="${link}" target="_blank"><i class="bi bi-file-earmark-pdf me-1"></i>Tải Giấy Báo Nhập Học</a></div>`
            : '';

        let leftDetails = '';
        let rightDetails = '';
        
        const getIconForLabel = (label) => {
            const l = label.toLowerCase();
            if (l.includes('họ và tên')) return '<i class="bi bi-person-badge text-primary"></i>';
            if (l.includes('ngày sinh')) return '<i class="bi bi-calendar3 text-success"></i>';
            if (l.includes('giới tính')) return '<i class="bi bi-gender-ambiguous text-info"></i>';
            if (l.includes('ngành')) return '<i class="bi bi-journal-text text-hl-navy"></i>';
            if (l.includes('điểm')) return '<i class="bi bi-star-fill text-hl-orange"></i>';
            if (l.includes('ưu tiên') || l.includes('kv') || l.includes('đt')) return '<i class="bi bi-award text-secondary"></i>';
            if (l.includes('thời gian')) return '<i class="bi bi-clock-history text-hl-navy"></i>';
            if (l.includes('địa điểm') || l.includes('tỉnh')) return '<i class="bi bi-geo-alt-fill text-hl-orange"></i>';
            if (l.includes('mã')) return '<i class="bi bi-upc-scan text-secondary"></i>';
            return '<i class="bi bi-info-square text-muted"></i>';
        };

        const addRow = (label, val, valClass = '') => {
            if (val && String(val).trim() !== '' && val !== '—' && val !== '-') {
                if (String(val).toLowerCase().includes('đang cập nhật')) {
                    valClass += ' text-danger fst-italic fw-normal';
                } else if (!valClass.includes('fw-bold') && !valClass.includes('fw-semibold')) {
                    valClass += ' fw-bold text-dark';
                }
                
                const l = label.toLowerCase();
                let bgClass = 'bg-light';
                let borderClass = 'border-light-subtle';
                let labelClass = 'text-muted';
                let hoverClasses = "this.classList.add('shadow-sm', 'bg-white', 'border-primary', 'border-opacity-25');";
                let hoverOutClasses = "this.classList.remove('shadow-sm', 'bg-white', 'border-primary', 'border-opacity-25');";

                if (l.includes('trúng tuyển ngành') || l.includes('thời gian')) {
                    bgClass = 'bg-hl-navy';
                    borderClass = 'border-hl-navy';
                    labelClass = 'text-hl-navy';
                    if (!valClass.includes('text-')) valClass += ' text-dark fw-bold';
                    hoverClasses = "this.classList.add('shadow-sm');";
                    hoverOutClasses = "this.classList.remove('shadow-sm');";
                } else if (l === 'điểm xét tuyển' || (l.includes('điểm') && !l.includes('tổng điểm')) || l.includes('địa điểm')) {
                    bgClass = 'bg-hl-orange';
                    borderClass = 'border-hl-orange';
                    labelClass = 'text-hl-orange';
                    valClass = 'fw-bold text-dark';
                    hoverClasses = "this.classList.add('shadow-sm');";
                    hoverOutClasses = "this.classList.remove('shadow-sm');";
                }

                const isRight = l.includes('trúng tuyển ngành') || (l.includes('điểm') && !l.includes('tổng điểm / đưt')) || l.includes('thời gian') || l.includes('địa điểm');
                const isStacked = l.includes('trúng tuyển ngành') || l.includes('địa điểm');

                let boxHtml = '';
                if (isStacked) {
                    boxHtml = `
                    <div class="px-3 py-2 rounded-2 ${bgClass} border ${borderClass} d-flex flex-column gap-2" style="transition: all 0.2s; cursor: default;" onmouseover="${hoverClasses}" onmouseout="${hoverOutClasses}">
                        <div class="d-flex align-items-center">
                            <div class="me-2 text-center flex-shrink-0" style="width: 16px; font-size: 0.85rem;">
                                ${getIconForLabel(label)}
                            </div>
                            <span class="${labelClass} fw-bold" style="font-size: 0.7rem; text-transform: uppercase;">${label}</span>
                        </div>
                        <div class="text-dark text-start mt-1 ${valClass}" style="font-size: 0.9rem; overflow-wrap: break-word; word-break: normal;">
                            ${val}
                        </div>
                    </div>`;
                } else {
                    boxHtml = `
                    <div class="px-2 py-2 px-sm-3 rounded-2 ${bgClass} border ${borderClass} d-flex justify-content-between align-items-center gap-2 gap-sm-3" style="transition: all 0.2s; cursor: default;" onmouseover="${hoverClasses}" onmouseout="${hoverOutClasses}">
                        <div class="d-flex align-items-center">
                            <div class="me-1 me-sm-2 text-center flex-shrink-0" style="width: 16px; font-size: 0.85rem;">
                                ${getIconForLabel(label)}
                            </div>
                            <span class="${labelClass} fw-bold" style="font-size: 0.7rem; text-transform: uppercase;">${label}</span>
                        </div>
                        <div class="text-dark text-end ms-2 ${valClass}" style="font-size: 0.9rem; overflow-wrap: break-word; word-break: normal;">
                            ${val}
                        </div>
                    </div>`;
                }

                if (isRight) {
                    if (l.includes('trúng tuyển ngành')) {
                        rightDetails = boxHtml + rightDetails;
                    } else {
                        rightDetails += boxHtml;
                    }
                } else {
                    leftDetails += boxHtml;
                }
            }
        };

        const excludeKeys = ['link giấy báo', 'tên ngành', 'trình độ', 'trạng thái hồ sơ', 'cccd', 'cmnd', 'căn cước', 'đt ưt', 'mã thm', 'mã hồ sơ', 'điểm ưu tiên giảm dần'];

        const sortedEntries = Object.entries(item).sort((a, b) => {
            const getRank = (key) => {
                const k = key.toLowerCase();
                if (k.includes('họ và tên')) return 1;
                if (k.includes('ngày sinh')) return 2;
                if (k.includes('giới tính')) return 3;
                if (k.includes('tỉnh')) return 4;
                if (k.includes('kv ưt') || k.includes('khu vực')) return 5;
                if (k.includes('ptxt') || k.includes('phương thức')) return 6;
                if (k.includes('tổng điểm')) return 7;
                return 99;
            };
            return getRank(a[0]) - getRank(b[0]);
        });

        sortedEntries.forEach(([key, val]) => {
            const lowerKey = key.toLowerCase();
            if (excludeKeys.some(ex => lowerKey.includes(ex))) return;

            let displayKey = key;
            let displayVal = val;
            let valClass = '';

            if (lowerKey === 'kv ưt' || lowerKey.includes('khu vực ưu tiên')) {
                displayKey = 'KV / ĐT Ưu tiên';
                const dtKey = Object.keys(item).find(k => k.toLowerCase() === 'đt ưt' || k.toLowerCase().includes('đối tượng ưu tiên'));
                const dtVal = dtKey ? item[dtKey] : '';
                displayVal = (dtVal && dtVal !== '-' && dtVal !== '—') ? `${val} / ${dtVal}` : val;
            } else if (lowerKey === 'mã ptxt' || lowerKey.includes('phương thức')) {
                displayKey = 'PTXT / THM';
                const thmKey = Object.keys(item).find(k => k.toLowerCase() === 'mã thm' || k.toLowerCase().includes('tổ hợp'));
                const thmVal = thmKey ? item[thmKey] : '';
                displayVal = (thmVal && thmVal !== '-' && thmVal !== '—') ? `${val} / ${thmVal}` : val;
            } else if (lowerKey === 'mã ngành') {
                displayKey = 'Trúng tuyển ngành';
                const heKey = Object.keys(item).find(k => k.toLowerCase() === 'trình độ' || k.toLowerCase().includes('hệ'));
                const tenNganhKey = Object.keys(item).find(k => k.toLowerCase() === 'tên ngành');
                const heVal = heKey ? item[heKey] : '';
                const tenNganhVal = tenNganhKey ? item[tenNganhKey] : '';
                
                const parts = [];
                if (heVal && heVal !== '-' && heVal !== '—') parts.push(heVal);
                if (tenNganhVal && tenNganhVal !== '-' && tenNganhVal !== '—') parts.push(tenNganhVal);
                parts.push(val);
                displayVal = parts.join(' / ');
            } else if (lowerKey === 'tổng điểm chưa có ưt (thang 30)' || lowerKey.includes('chưa có ưt')) {
                displayKey = 'Tổng điểm / ĐƯT';
                const utKey = Object.keys(item).find(k => k.toLowerCase() === 'điểm ưu tiên giảm dần' || k.toLowerCase().includes('ưu tiên giảm dần'));
                const utVal = utKey ? item[utKey] : '';
                displayVal = (utVal && utVal !== '-' && utVal !== '—') ? `${val} / ${utVal}` : val;
            }

            addRow(displayKey, displayVal, valClass);
        });


        html += `
        <div class="col">
            <div class="result-card h-100 d-flex flex-column mb-3 shadow-sm border-0" style="border-radius: 12px;">
                <div class="card-top" style="border-radius: 12px 12px 0 0; padding: 12px 20px;">
                    <span class="nv-label d-flex align-items-center flex-wrap gap-2" style="font-size: 0.9rem;">
                        ${hsBadge}
                    </span>
                    ${badgeHtml}
                </div>
                <div class="card-body-mobile p-3 flex-grow-1 bg-white">
                    <div class="row g-2">
                        <div class="col-12 col-md-6 d-flex flex-column gap-2">
                            ${leftDetails}
                        </div>
                        <div class="col-12 col-md-6 d-flex flex-column gap-2">
                            ${rightDetails}
                        </div>
                    </div>
                </div>
                ${dlBar}
            </div>
        </div>`;
    });
    html += `</div>`;

    c.innerHTML = html;
}
</script>
</body>
</html>
