<?php
session_start();
require_once 'includes/config.php';
require_once 'includes/format-currency.php';
require_once 'includes/cai-dat-helper.php';
$_anh_bia_tin = layAnhBiaTrang($pdo, 'tin_su_kien');

$ma_gioi_thieu_sẵn = '';
$id_thanh_vien_hien_tai = (int)($_SESSION['nguoi_dung_id'] ?? $_SESSION['user_id'] ?? 0);
$ma_gioi_thieu_thanh_vien = '';

if ($id_thanh_vien_hien_tai > 0) {
    $stmt_thanh_vien = $pdo->prepare("SELECT ma_gioi_thieu FROM thanh_vien WHERE id = ? LIMIT 1");
    $stmt_thanh_vien->execute([$id_thanh_vien_hien_tai]);
    $thanh_vien_hien_tai = $stmt_thanh_vien->fetch();
    if ($thanh_vien_hien_tai) {
        $ma_gioi_thieu_thanh_vien = $thanh_vien_hien_tai['ma_gioi_thieu'] ?? '';
    }
}

if (isset($_GET['ref']) && trim($_GET['ref']) !== '') {
    $ma_gioi_thieu_sẵn = strtoupper(trim($_GET['ref']));
}

try {
    $stmt_tin = $pdo->query("SELECT * FROM tin_tuc_su_kien WHERE loai_tin = 'noi_bat' ORDER BY ngay_tao DESC LIMIT 100");
    $danh_sach_tin = $stmt_tin->fetchAll(PDO::FETCH_ASSOC);
    
    $tin_am_nhac = [];
    $tin_hoi_hoa = [];
    foreach ($danh_sach_tin as $tin) {
        $phan_loai_json = $tin['phan_loai'] ?? '[]';
        $phan_loai_arr = json_decode($phan_loai_json, true) ?? [];
        
        if (in_array('nhac', $phan_loai_arr)) {
            $tin_am_nhac[] = $tin;
        }
        if (in_array('hoa', $phan_loai_arr)) {
            $tin_hoi_hoa[] = $tin;
        }
    }
} catch (Exception $e) {
    $tin_am_nhac = [];
    $tin_hoi_hoa = [];
}

try {
    $stmt_sk = $pdo->query("SELECT * FROM su_kien WHERE trang_thai IN ('dang_mo', 'da_chot') ORDER BY ngay_dien_ra ASC LIMIT 10");
    $danh_sach_su_kien = $stmt_sk->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $danh_sach_su_kien = [];
}

function hien_thi_mo_ta_an_toan($noi_dung) {
    if ($noi_dung === null) return '';
    $noi_dung = trim((string)$noi_dung);
    if ($noi_dung === '') return '';
    $noi_dung = html_entity_decode($noi_dung, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    $noi_dung = preg_replace('#</p>#i', '<br>', $noi_dung);
    $noi_dung = preg_replace('#<p[^>]*>#i', '', $noi_dung);
    $noi_dung = strip_tags($noi_dung, '<br>');
    $noi_dung = preg_replace('/\s+/', ' ', $noi_dung);
    $noi_dung = str_replace(['<br>', '<br />'], ['<br>', '<br>'], $noi_dung);
    return $noi_dung;
}

function render_tin_noi_bat($tin_noi_bat, $icon = '🎵') {
    ?>
    <div class="luoi-noi-bat">
        <div class="the-tin tin-noi-bat-lon">
            <div class="anh-tin" style="background: #f8f9fa;">
                <?php if (!empty($tin_noi_bat[0]['anh_bia'])): ?>
                    <img src="<?php echo htmlspecialchars($tin_noi_bat[0]['anh_bia'], ENT_QUOTES); ?>" alt="<?php echo htmlspecialchars($tin_noi_bat[0]['tieu_de'], ENT_QUOTES); ?>" class="anh-tin-img">
                <?php else: ?>
                    <?php echo $tin_noi_bat[0]['bieu_tuong'] ?? $icon; ?>
                <?php endif; ?>
            </div>
            <div class="noi-dung-tin">
                <div class="ngay-tin"><?php echo !empty($tin_noi_bat[0]['ngay_tao']) ? date('d/m/Y', strtotime($tin_noi_bat[0]['ngay_tao'])) : 'Chưa xác định'; ?></div>
                <h3 class="tieu-de-tin"><?php echo htmlspecialchars($tin_noi_bat[0]['tieu_de']); ?></h3>
                <div class="mo-ta-tin"><?php echo hien_thi_mo_ta_an_toan($tin_noi_bat[0]['mo_ta'] ?? ''); ?></div>
                <a href="chi-tiet-tin-tuc.php?id=<?php echo (int)$tin_noi_bat[0]['id']; ?>" class="nut-xem-chi-tiet">Xem chi tiết →</a>
            </div>
        </div>
        
        <div class="luoi-tin-nho">
            <?php for ($i = 1; $i < 4 && $i < count($tin_noi_bat); $i++): ?>
            <div class="the-tin tin-noi-bat-nho">
                <div class="anh-tin" style="background: #f8f9fa;">
                    <?php if (!empty($tin_noi_bat[$i]['anh_bia'])): ?>
                        <img src="<?php echo htmlspecialchars($tin_noi_bat[$i]['anh_bia'], ENT_QUOTES); ?>" alt="<?php echo htmlspecialchars($tin_noi_bat[$i]['tieu_de'], ENT_QUOTES); ?>" class="anh-tin-img">
                    <?php else: ?>
                        <?php echo $tin_noi_bat[$i]['bieu_tuong'] ?? $icon; ?>
                    <?php endif; ?>
                </div>
                <div class="noi-dung-tin">
                    <div class="ngay-tin"><?php echo !empty($tin_noi_bat[$i]['ngay_tao']) ? date('d/m/Y', strtotime($tin_noi_bat[$i]['ngay_tao'])) : 'Chưa xác định'; ?></div>
                    <h3 class="tieu-de-tin"><?php echo htmlspecialchars($tin_noi_bat[$i]['tieu_de']); ?></h3>
                    <div class="mo-ta-tin"><?php echo hien_thi_mo_ta_an_toan($tin_noi_bat[$i]['mo_ta'] ?? ''); ?></div>
                    <a href="chi-tiet-tin-tuc.php?id=<?php echo (int)$tin_noi_bat[$i]['id']; ?>" class="nut-xem-chi-tiet">Xem chi tiết →</a>
                </div>
            </div>
            <?php endfor; ?>
        </div>
    </div>
    <?php
}

function render_tin_moi($tin_moi, $icon = '🎵') {
    ?>
    <h3 style="color: #1864ab; margin: 30px 0 15px 0; font-size: 16px;">Bài viết mới</h3>
    <div class="luoi-tin">
        <?php foreach ($tin_moi as $tin): ?>
        <div class="the-tin">
            <div class="anh-tin" style="background: #f8f9fa;">
                <?php if (!empty($tin['anh_bia'])): ?>
                    <img src="<?php echo htmlspecialchars($tin['anh_bia'], ENT_QUOTES); ?>" alt="<?php echo htmlspecialchars($tin['tieu_de'], ENT_QUOTES); ?>" class="anh-tin-img">
                <?php else: ?>
                    <?php echo $tin['bieu_tuong'] ?? $icon; ?>
                <?php endif; ?>
            </div>
            <div class="noi-dung-tin">
                <div class="ngay-tin"><?php echo !empty($tin['ngay_tao']) ? date('d/m/Y', strtotime($tin['ngay_tao'])) : 'Chưa xác định'; ?></div>
                <h3 class="tieu-de-tin"><?php echo htmlspecialchars($tin['tieu_de']); ?></h3>
                <div class="mo-ta-tin"><?php echo hien_thi_mo_ta_an_toan($tin['mo_ta'] ?? ''); ?></div>
                <a href="chi-tiet-tin-tuc.php?id=<?php echo (int)$tin['id']; ?>" class="nut-xem-chi-tiet">Xem chi tiết →</a>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php
}
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tin Tức & Sự Kiện - PHẠM NGỌC TV</title>
    <link rel="icon" type="image/png" href="images/icon.png">
    <link rel="apple-touch-icon" href="images/icon.png">
    <link rel="stylesheet" href="includes/style.css">
    <style>
        body { background-color: #f8f9fa; margin: 0; color: #333; }
        
        .khu-vuc-hero { background: #1864ab; color: white; padding: 50px 20px; text-align: center; background-size: cover; background-position: center; position: relative; }
        .khu-vuc-hero::before { content:''; position:absolute; inset:0; background:rgba(24,100,171,0.72); }
        .khu-vuc-hero > * { position: relative; z-index: 1; }
        .khu-vuc-hero h1 { margin: 10px 0; font-size: 32px; }
        .khu-vuc-hero p { margin: 0; font-size: 16px; opacity: 0.9; }
        .nut-tro-ve { display: inline-block; padding: 8px 20px; background: rgba(255,255,255,0.2); color: white; text-decoration: none; border-radius: 20px; font-size: 14px; margin-bottom: 20px; }
        .nut-tro-ve:hover { background: rgba(255,255,255,0.3); }

        .vung-noi-dung { max-width: 1200px; margin: 0 auto; padding: 30px 20px; box-sizing: border-box; }

        .luoi-tin { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 25px; }
        .the-tin { background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.05); border: 1px solid #e1e8ed; transition: 0.3s; display: flex; flex-direction: column; }
        .the-tin:hover { transform: translateY(-5px); box-shadow: 0 10px 25px rgba(0,0,0,0.1); border-color: #1864ab; }
        .anh-tin { width: 100%; aspect-ratio: 600 / 350; display: flex; align-items: center; justify-content: center; font-size: 50px; background: #f8f9fa; border-bottom: 1px solid #f1f3f5; overflow: hidden; cursor: pointer; }
        .anh-tin-img { width: 100%; height: 100%; object-fit: cover; object-position: center; display: block; }
        .noi-dung-tin { padding: 20px; flex: 1; display: flex; flex-direction: column; }
        .tieu-de-tin { font-size: 16px; font-weight: bold; color: #1864ab; margin: 0 0 10px 0; line-height: 1.4; cursor: pointer; }
        .tieu-de-tin:hover { text-decoration: underline; }
        .mo-ta-tin { font-size: 13px; color: #555; line-height: 1.5; margin-bottom: 15px; flex: 1; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; cursor: pointer; }
        .mo-ta-tin:hover { color: #1864ab; }
        .ngay-tin { font-size: 12px; color: #999; margin-bottom: 12px; }
        .nut-xem-chi-tiet { display: none; }

        .luoi-noi-bat { display: grid; grid-template-columns: 2fr 1fr; gap: 25px; margin-bottom: 40px; }
        .tin-noi-bat-lon { grid-row: 1 / 3; }
        .tin-noi-bat-lon .anh-tin { aspect-ratio: 600 / 400; }
        .luoi-tin-nho { display: grid; grid-template-columns: 1fr; gap: 25px; }
        .tin-noi-bat-nho { display: flex; flex-direction: row; }
        .tin-noi-bat-nho .anh-tin { aspect-ratio: 1 / 1; width: 120px; min-width: 120px; height: 120px; border-bottom: none; border-right: 1px solid #f1f3f5; }
        .tin-noi-bat-nho .noi-dung-tin { padding: 12px; }
        .tin-noi-bat-nho .tieu-de-tin { font-size: 13px; margin-bottom: 6px; }
        .tin-noi-bat-nho .mo-ta-tin { font-size: 11px; margin-bottom: 8px; -webkit-line-clamp: 2; }
        .tin-noi-bat-nho .ngay-tin { font-size: 11px; margin-bottom: 6px; }

        .tieu-de-linh-vuc { color: #1864ab; margin: 40px 0 20px 0; font-size: 22px; font-weight: bold; border-bottom: 3px solid #1864ab; padding-bottom: 10px; }
        .tieu-de-linh-vuc:first-of-type { margin-top: 0; }

        .sidebar-su-kien { background: white; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); border: 1px solid #e1e8ed; overflow: hidden; }
        .sidebar-header { background: #e03131; color: white; padding: 16px; font-weight: bold; font-size: 16px; }
        .sidebar-content { padding: 20px; }
        .su-kien-item { padding: 12px 0; border-bottom: 1px solid #f1f3f5; cursor: pointer; }
        .su-kien-item:hover { background-color: #f8f9fa; padding: 12px 8px; margin: 0 -8px; }
        .su-kien-item:last-child { border-bottom: none; }
        .su-kien-title { font-weight: 600; color: #1864ab; font-size: 14px; line-height: 1.4; margin-bottom: 6px; }
        .su-kien-date { font-size: 12px; color: #999; }

        .sidebar-su-kien-mobile { display: none !important; margin-bottom: 30px; background: white; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); border: 1px solid #e1e8ed; overflow: hidden; }

        @media (max-width: 768px) {
            .khu-vuc-hero h1 { font-size: 24px; }
            
            .sidebar-su-kien-mobile { display: block !important; margin-bottom: 30px; }
            .sidebar-su-kien { display: none !important; }
            
            .grid-desktop { grid-template-columns: 1fr !important; }
            
            .luoi-noi-bat { display: grid; grid-template-columns: 1fr; gap: 25px; margin-bottom: 40px; }
            .luoi-noi-bat > * { flex: none; }
            .tin-noi-bat-lon { grid-row: auto; }
            .luoi-tin-nho { display: grid; grid-template-columns: 1fr; gap: 25px; }
            .tin-noi-bat-nho { display: flex; flex-direction: row; }
            .tin-noi-bat-nho .anh-tin { aspect-ratio: 1 / 1; width: 100px; min-width: 100px; height: 100px; }
            
            .luoi-tin { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>

    <div class="khu-vuc-hero"<?php if($_anh_bia_tin): ?> style="background-image:url('<?php echo htmlspecialchars($_anh_bia_tin); ?>')"<?php endif; ?>>
        <a href="index.php" class="nut-tro-ve">⬅ Trở về Sảnh chính</a>
        <h1>📰 Tin Tức & Sự Kiện</h1>
        <p>Cập nhật những thông tin mới nhất về Âm Nhạc, Hội Họa và các sự kiện nghệ thuật</p>
    </div>

    <div class="vung-noi-dung">
        <!-- MOBILE: SIDEBAR SỰ KIỆN LÊN TRÊN -->
        <div class="sidebar-su-kien-mobile">
            <div class="sidebar-header">📅 Sự Kiện Sắp Tới</div>
            <div class="sidebar-content">
                <?php if (!empty($danh_sach_su_kien)): ?>
                    <?php foreach ($danh_sach_su_kien as $sk): ?>
                    <div class="su-kien-item" onclick="window.location.href='thong-bao-su-kien.php?id=<?php echo (int)$sk['id']; ?>'">
                        <div class="su-kien-title"><?php echo htmlspecialchars($sk['ten_su_kien'] ?? $sk['tieu_de'] ?? 'Sự kiện'); ?></div>
                        <div class="su-kien-date">
                            📍 <?php echo !empty($sk['ngay_dien_ra']) ? date('d/m/Y', strtotime($sk['ngay_dien_ra'])) : 'Chưa xác định'; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p style="color: #999; font-size: 13px; text-align: center;">Chưa có sự kiện nào được lên lịch.</p>
                <?php endif; ?>
            </div>
        </div>

        <div style="display: grid; grid-template-columns: 1fr 300px; gap: 30px; align-items: start;" class="grid-desktop">
            
            <!-- DANH SÁCH TIN TỨC -->
            <div>
                <!-- ÂM NHẠC -->
                <?php if (!empty($tin_am_nhac)): ?>
                    <h2 class="tieu-de-linh-vuc">🎵 Âm Nhạc</h2>
                    <?php 
                    $tin_noi_bat = array_slice($tin_am_nhac, 0, 4);
                    $tin_moi = array_slice($tin_am_nhac, 4);
                    if (count($tin_noi_bat) > 0) render_tin_noi_bat($tin_noi_bat, '🎵');
                    if (!empty($tin_moi)) render_tin_moi($tin_moi, '🎵');
                    ?>
                <?php endif; ?>

                <!-- HỘI HỌA -->
                <?php if (!empty($tin_hoi_hoa)): ?>
                    <h2 class="tieu-de-linh-vuc">🎨 Hội Họa</h2>
                    <?php 
                    $tin_noi_bat = array_slice($tin_hoi_hoa, 0, 4);
                    $tin_moi = array_slice($tin_hoi_hoa, 4);
                    if (count($tin_noi_bat) > 0) render_tin_noi_bat($tin_noi_bat, '🎨');
                    if (!empty($tin_moi)) render_tin_moi($tin_moi, '🎨');
                    ?>
                <?php endif; ?>

                <!-- LỜI TRI ÂN -->
                <?php
                try {
                    $ds_tri_an = $pdo->query("SELECT ta.*, tv.ho_ten, tv.anh_dai_dien FROM tri_an ta LEFT JOIN thanh_vien tv ON tv.id = ta.thanh_vien_id WHERE ta.trang_thai = 'da_duyet' ORDER BY ta.ngay_tao DESC LIMIT 12")->fetchAll();
                } catch (Exception $e) { $ds_tri_an = []; }
                ?>
                <?php if (!empty($ds_tri_an)): ?>
                    <h2 class="tieu-de-linh-vuc" style="color:#6f42c1; border-color:#6f42c1;">💌 Lời Tri ân Cộng đồng</h2>
                    <div class="luoi-tin">
                        <?php foreach ($ds_tri_an as $ta): ?>
                        <div class="the-tin" style="border-left: 4px solid #6f42c1;">
                            <div class="noi-dung-tin">
                                <div style="display:flex; align-items:center; gap:10px; margin-bottom:12px;">
                                    <?php if (!empty($ta['anh_dai_dien'])): ?>
                                        <img src="<?php echo htmlspecialchars($ta['anh_dai_dien']); ?>" style="width:40px;height:40px;border-radius:50%;object-fit:cover;">
                                    <?php else: ?>
                                        <div style="width:40px;height:40px;border-radius:50%;background:#6f42c1;color:white;display:flex;align-items:center;justify-content:center;font-weight:bold;font-size:16px;"><?php echo mb_substr($ta['ho_ten'] ?? '?', 0, 1, 'UTF-8'); ?></div>
                                    <?php endif; ?>
                                    <div>
                                        <div style="font-weight:bold;font-size:14px;color:#333;"><?php echo htmlspecialchars($ta['ho_ten'] ?? 'Thành viên'); ?></div>
                                        <div class="ngay-tin"><?php echo date('d/m/Y', strtotime($ta['ngay_tao'])); ?></div>
                                    </div>
                                </div>
                                <div style="font-size:14px;color:#555;line-height:1.6;font-style:italic;">"<?php echo nl2br(htmlspecialchars($ta['noi_dung'])); ?>"</div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

            <!-- DESKTOP: SIDEBAR SỰ KIỆN BÊN PHẢI -->
            <div class="sidebar-su-kien" style="position: sticky; top: 20px;">
                <div class="sidebar-header">📅 Sự Kiện Sắp Tới</div>
                <div class="sidebar-content">
                    <?php if (!empty($danh_sach_su_kien)): ?>
                        <?php foreach ($danh_sach_su_kien as $sk): ?>
                        <div class="su-kien-item" onclick="window.location.href='thong-bao-su-kien.php?id=<?php echo (int)$sk['id']; ?>'">
                            <div class="su-kien-title"><?php echo htmlspecialchars($sk['ten_su_kien'] ?? $sk['tieu_de'] ?? 'Sự kiện'); ?></div>
                            <div class="su-kien-date">
                                📍 <?php echo !empty($sk['ngay_dien_ra']) ? date('d/m/Y', strtotime($sk['ngay_dien_ra'])) : 'Chưa xác định'; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p style="color: #999; font-size: 13px; text-align: center;">Chưa có sự kiện nào được lên lịch.</p>
                    <?php endif; ?>
                </div>
            </div>

        </div>
    </div>

    <?php require_once 'includes/menu-dien-thoai.php'; ?>
    <script>
        document.querySelectorAll('.anh-tin, .tieu-de-tin, .mo-ta-tin').forEach(el => {
            el.addEventListener('click', function() {
                const link = this.closest('.the-tin').querySelector('a.nut-xem-chi-tiet');
                if (link) window.location.href = link.href;
            });
        });
    </script>
</body>
</html>
