<?php
/* =====================================================================
   test.php — Lập lá số & Luận giải Tứ Hóa (báo cáo đẹp)
   ===================================================================== */

// ---------- Helpers giống laso.php ----------------------------------
function buildLasoUrl(string $ngay, string $gio, string $gioitinh): string {
    $map = [
        ['1','2',  '1h-2h59'],  ['3','4',  '3h-4h59'],
        ['5','6',  '5h-6h59'],  ['7','8',  '7h-8h59'],
        ['9','10', '9h-10h59'], ['11','12','11h-12h59'],
        ['13','14','13h-14h59'],['15','16','15h-16h59'],
        ['17','18','17h-18h59'],['19','20','19h-20h59'],
        ['21','22','21h-22h59'],['23','0', '23h-0h59'],
    ];
    $khoanggio = '';
    foreach ($map as [$a, $b, $range]) {
        if ($gio === $a || $gio === $b) { $khoanggio = $range; break; }
    }

    // Giờ 23 → dịch ngày +1
    if ($gio === '23') {
        $ngay = date('Y-m-d', strtotime($ngay) + 86400);
    }

    $s = date_parse_from_format('Y-m-d', $ngay);
    $d = $s['day']; $m = $s['month']; $y = $s['year'];

    if ($gioitinh === '1') {
        $folder  = "la-so-nam-gioi/nam-{$y}/thang-{$m}/ngay-{$d}/";
        $tenfile = "{$d}-{$m}-{$y}-{$khoanggio}-nam-dl-la-so-tu-vi_lg_luan_giai_la_so_tu_vi.html";
    } else {
        $folder  = "la-so-nu-gioi/nam-{$y}/thang-{$m}/ngay-{$d}/";
        $tenfile = "{$d}-{$m}-{$y}-{$khoanggio}-nu-dl-la-so-tu-vi_lg_luan_giai_la_so_tu_vi.html";
    }
    return "https://laso.khamthientuhoa.com/{$folder}{$tenfile}";
}

function buildImageUrl(string $ngay, string $gio, string $gioitinh): string {
    // Giống buildLasoUrl nhưng trả về URL ảnh _ktm.jpg
    $url = buildLasoUrl($ngay, $gio, $gioitinh);
    return str_replace('_lg_luan_giai_la_so_tu_vi.html', '_ktm.jpg', $url);
}

// ---------- Lấy path local từ URL -----------------------------------
function localPathFromUrl(string $url): string {
    // URL: https://laso.khamthientuhoa.com/{folder}{file}
    // File nằm tại: /var/www/html/laso/{folder}{file}
    $base    = 'https://laso.khamthientuhoa.com/';
    $baseHttp = 'http://laso.khamthientuhoa.com/';
    if (str_starts_with($url, $base)) {
        $rel = substr($url, strlen($base));
    } elseif (str_starts_with($url, $baseHttp)) {
        $rel = substr($url, strlen($baseHttp));
    } else {
        $rel = parse_url($url, PHP_URL_PATH);
        $rel = ltrim($rel, '/');
    }
    return '/var/www/html/laso/' . $rel;
}

// ---------- Fetch & parse -------------------------------------------
function fetchHtml(string $url): string {
    // Ưu tiên đọc file local (nhanh, không bị chặn)
    $localPath = localPathFromUrl($url);
    if (file_exists($localPath)) {
        return file_get_contents($localPath) ?: '';
    }
    // Fallback: HTTP
    foreach ([$url, str_replace('https://', 'http://', $url)] as $u) {
        $ctx = stream_context_create(['http' => [
            'timeout'    => 20,
            'user_agent' => 'Mozilla/5.0',
            'header'     => "Accept-Language: vi-VN,vi;q=0.9\r\n",
        ]]);
        $html = @file_get_contents($u, false, $ctx);
        if ($html) return $html;
    }
    return '';
}

// Phân tích HTML thành sections, giữ nguyên màu font gốc (green/red/fuchsia)
function parseSections(string $html): array {
    // Chuẩn hóa encoding
    if (!preg_match('//u', $html)) {
        $html = mb_convert_encoding($html, 'UTF-8', 'auto');
    }

    // --- Xóa hoàn toàn các block không cần thiết ---
    // iframe (dù có hay không closing tag)
    $html = preg_replace('/<iframe[^>]*>.*?<\/iframe>/si', '', $html);
    $html = preg_replace('/<iframe[^>]*>/si', '', $html);
    $html = preg_replace('/<\/iframe>/si', '', $html);
    // img (ảnh lá số)
    $html = preg_replace('/<img[^>]*\/?>/si', '', $html);
    // script / style / link
    $html = preg_replace('/<(script|style)[^>]*>.*?<\/\1>/si', '', $html);
    $html = preg_replace('/<(script|style|link|meta)[^>]*\/?>/si', '', $html);

    // Chuẩn hóa newline markers
    $html = preg_replace('/<br\s*\/?>/i', "\n", $html);
    $html = preg_replace('/<\/tr>/i', "\n", $html);
    $html = preg_replace('/<\/p>/i',  "\n", $html);

    // Loại bỏ thẻ không liên quan đến nội dung (giữ font/b để nhận màu)
    $html = preg_replace('/<\/?(table|tr|td|tbody|thead|ul|ol|li|div|span|a|u|i|em|h[1-6])[^>]*>/si', '', $html);

    // Giữ lại font/b để dùng phân loại
    $lines_raw = explode("\n", $html);
    $lines_raw = array_values(array_filter(array_map('trim', $lines_raw)));

    $sections   = [];
    $current    = ['title' => 'Thông Tin', 'content' => [], 'type' => 'info', 'idx' => 0];
    $sectionIdx = 1;

    $sectionPatterns = [
        '/Lập\s+Cực\s+cung\s+(.+)/iu'                            => 'lapCuc',
        '/KẾT\s+LUẬN\s+CUNG\s*/iu'                               => 'ketLuan',
        '/LUẬN\s+\S.{2,25}\s+CẢ\s+ĐỜI/iu'                       => 'luan',
        '/Tổng\s+Quan\s+cả\s+đời/iu'                             => 'tongQuanDoi',
        '/Tổng\s+Quan\s+năm\s+\d{4}/iu'                          => 'tongQuan',
        '/Tổng\s+Quan\s+năm\s+\d{4}\s+có\s+luận\s+giải/iu'      => 'lapCucYear',
        '/Xem\s+vận\s+hạn\s+năm\s+\d{4}/iu'                     => 'tongQuan',
    ];

    foreach ($lines_raw as $raw) {
        // Lấy text thuần (bỏ tag)
        $text = trim(strip_tags($raw));
        $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        $text = preg_replace('/\s+/', ' ', $text);
        if ($text === '') continue;

        // Phát hiện section header
        $matched = false;
        foreach ($sectionPatterns as $pat => $type) {
            if (preg_match($pat, $text)) {
                if (!empty($current['content'])) $sections[] = $current;
                $current = [
                    'title'   => $text,
                    'content' => [],
                    'type'    => $type,
                    'idx'     => $sectionIdx++,
                ];
                $matched = true;
                break;
            }
        }
        if (!$matched) {
            // Lọc bỏ dòng tiếp thị / quảng cáo / liên kết không cần thiết
            $skipPatterns = [
                '/Liên\s+hệ\s+với\s+nhóm/iu',
                '/nhóm\s+Khâm\s+Thiên/iu',
                '/zalolink/i',
                '/facebook\.com/i',
                '/youtube\.com/i',
                '/Ảnh\s+Lá\s+số/iu',
                '/Quay\s+lại\s+trang/iu',
                '/tư\s+vấn\s+hóa\s+giải/iu',
                '/tham\s+gia\s+nhóm/iu',
                '/Lớp\s+Học\s+Tứ\s+Hóa/iu',
                '/khosachquy/i',
                '/khamthientuhoa\.com\/zalo/i',
            ];
            $skip = false;
            foreach ($skipPatterns as $p) {
                if (preg_match($p, $text)) { $skip = true; break; }
            }
            if ($skip) continue;

            // Phân loại màu từ font tag gốc
            $cls = 'neutral';
            if (preg_match('/<font[^>]+color\s*=\s*["\']?green/i', $raw))   $cls = 'good';
            if (preg_match('/<font[^>]+color\s*=\s*["\']?red/i', $raw))     $cls = 'bad';
            if (preg_match('/<font[^>]+color\s*=\s*["\']?fuchsia/i', $raw)) $cls = 'mixed';

            $current['content'][] = ['text' => $text, 'cls' => $cls];
        }
    }
    if (!empty($current['content'])) $sections[] = $current;

    if (empty($sections)) {
        // Fallback: dump tất cả text thành 1 section
        $allText = html_entity_decode(strip_tags(preg_replace('/<br\s*\/?>/i', "\n", $html)), ENT_QUOTES | ENT_HTML5, 'UTF-8');
        $lines   = array_values(array_filter(array_map('trim', explode("\n", $allText))));
        $sections = [['title' => 'Nội Dung Luận Giải', 'content' => array_map(fn($l) => ['text' => $l, 'cls' => 'neutral'], $lines), 'type' => 'luan', 'idx' => 0]];
    }
    return $sections;
}

// Render một dòng với class màu và highlight năm/tuổi
function renderLine(array $item): string {
    $text = htmlspecialchars($item['text'], ENT_QUOTES, 'UTF-8');
    $cls  = $item['cls'] ?? 'neutral';

    // Nổi bật năm
    $text = preg_replace('/Năm\s+(\d{4})/u', '<span class="year">Năm $1</span>', $text);
    // Nổi bật tuổi
    $text = preg_replace('/(\d{1,3})\s*[–\-]\s*(\d{1,3})\s+Tuổi/u', '<span class="age">$1-$2 Tuổi</span>', $text);
    $text = preg_replace('/(\d{1,3})\s+Tuổi/u', '<span class="age">$1 Tuổi</span>', $text);
    // Đại vận
    $text = preg_replace('/Đại\s+Vận\s+(\d+)/iu', '<span class="dv">Đại Vận $1</span>', $text);
    // Tháng
    $text = preg_replace('/(Tháng tốt[^:]*:\s*)([\d,\s]+)/iu',
        '<span class="month-good">✦ $1$2</span>', $text);
    $text = preg_replace('/(Tháng xấu[^:]*:\s*)([\d,\s]+)/iu',
        '<span class="month-bad">✗ $1$2</span>', $text);

    $cssClass = match($cls) {
        'good'    => 'line-good',
        'bad'     => 'line-bad',
        'mixed'   => 'line-mixed',
        default   => 'line-neutral',
    };
    return "<p class=\"{$cssClass}\">{$text}</p>";
}

// ---- Đếm bài viết từ khamthientuhoa.com (cache 6 giờ) ----
function getPostCount(): string {
    $cacheFile = __DIR__ . '/data/post_count.cache';
    // Dùng cache nếu còn mới (< 6 giờ)
    if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < 21600) {
        return trim(file_get_contents($cacheFile));
    }
    $ctx   = stream_context_create(['http' => ['timeout' => 5, 'user_agent' => 'Mozilla/5.0']]);
    $count = '';

    // Cách chính xác nhất: WordPress REST API trả về header X-WP-Total
    $headers = @get_headers('https://khamthientuhoa.com/wp-json/wp/v2/posts?per_page=1&status=publish&_fields=id', 1, $ctx);
    if ($headers) {
        // get_headers trả về mảng, header có thể là X-WP-Total hoặc x-wp-total
        foreach ($headers as $key => $val) {
            if (strtolower((string)$key) === 'x-wp-total') {
                $count = is_array($val) ? $val[0] : $val;
                break;
            }
        }
    }

    // Lưu cache nếu lấy được
    if ($count && is_numeric(trim($count)) && is_dir(__DIR__ . '/data')) {
        file_put_contents($cacheFile, trim($count));
        return trim($count);
    }

    // Fallback: giữ cache cũ nếu có, hoặc dùng mặc định
    if (file_exists($cacheFile)) {
        return trim(file_get_contents($cacheFile));
    }
    return '158+';
}
$postCount = getPostCount();

// ---- Xử lý form submit ----
$result   = null;
$error    = null;
$sourceUrl = null;
$birthInfo = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $ngay     = trim($_POST['date']     ?? '');
    $gio      = trim($_POST['time']     ?? '');
    $gioitinh = trim($_POST['gender']   ?? '');

    if ($ngay && $gio !== '' && $gioitinh) {
        $sourceUrl = buildLasoUrl($ngay, $gio, $gioitinh);
        $imageUrl  = buildImageUrl($ngay, $gio, $gioitinh);

        $s = date_parse_from_format('Y-m-d', $ngay);
        $gioLabel = [
            '0'=>'0h (Tý sớm)','1'=>'1h','2'=>'2h (Sửu)','3'=>'3h','4'=>'4h (Dần)',
            '5'=>'5h','6'=>'6h (Mão)','7'=>'7h','8'=>'8h (Thìn)','9'=>'9h',
            '10'=>'10h (Tỵ)','11'=>'11h','12'=>'12h (Ngọ)','13'=>'13h',
            '14'=>'14h (Mùi)','15'=>'15h','16'=>'16h (Thân)','17'=>'17h',
            '18'=>'18h (Dậu)','19'=>'19h','20'=>'20h (Tuất)','21'=>'21h',
            '22'=>'22h (Hợi)','23'=>'23h (Tý muộn)',
        ];
        $birthInfo = [
            'Ngày sinh'  => "{$s['day']}/{$s['month']}/{$s['year']}",
            'Giờ sinh'   => $gioLabel[$gio] ?? "{$gio}h",
            'Giới tính'  => $gioitinh === '1' ? 'Nam' : 'Nữ',
            'Dương lịch' => date('d/m/Y', strtotime($ngay)),
        ];

        $rawHtml  = fetchHtml($sourceUrl);
        if ($rawHtml) {
            $result = parseSections($rawHtml);
        } else {
            $error = "Không thể tải dữ liệu từ hệ thống lá số. Vui lòng kiểm tra lại thông tin hoặc thử lại sau.";
        }
    } else {
        $error = "Vui lòng điền đầy đủ ngày sinh, giờ sinh và giới tính.";
    }
}

// Màu icon theo type
$typeIcon = [
    'info'         => '✦',
    'tongQuan'     => '◈',
    'tongQuanDoi'  => '◉',
    'luan'         => '❖',
    'lapCuc'       => '◇',
    'ketLuan'      => '★',
];
$typeLabel = [
    'info'         => 'Thông tin',
    'tongQuan'     => 'Tổng quan năm',
    'tongQuanDoi'  => 'Tổng quan cả đời',
    'luan'         => 'Luận giải',
    'lapCuc'       => 'Lập cực',
    'ketLuan'      => 'Kết luận',
];
?>
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lập Lá Số Tử Vi Miễn Phí — Khâm Thiên Tứ Hóa Bắc Phái</title>
<meta name="description" content="Công cụ lập và luận giải lá số Tử Vi Đẩu Số theo trường phái Khâm Thiên Tứ Hóa Bắc Phái. Nhập ngày sinh, giờ sinh, giới tính để nhận luận giải chuyên sâu miễn phí.">
<link rel="canonical" href="https://laso.khamthientuhoa.com/">
<meta property="og:type" content="website">
<meta property="og:url" content="https://laso.khamthientuhoa.com/">
<meta property="og:title" content="Lập Lá Số Tử Vi Miễn Phí — Khâm Thiên Tứ Hóa Bắc Phái">
<meta property="og:description" content="Công cụ lập và luận giải lá số Tử Vi Đẩu Số theo trường phái Khâm Thiên Tứ Hóa Bắc Phái miễn phí.">
<meta property="og:image" content="https://laso.khamthientuhoa.com/og-image.php">
<meta property="og:locale" content="vi_VN">
<meta property="og:site_name" content="Khâm Thiên Tứ Hóa">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Lập Lá Số Tử Vi Miễn Phí — Khâm Thiên Tứ Hóa">
<meta name="twitter:description" content="Công cụ lập và luận giải lá số Tứ Hóa Bắc Phái miễn phí.">
<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;600;700&family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" crossorigin="anonymous">
<?php
$schema = [
    [
        "@context" => "https://schema.org",
        "@type" => "WebApplication",
        "name" => "Lập Lá Số Khâm Thiên Tứ Hóa",
        "url" => "https://laso.khamthientuhoa.com",
        "description" => "Công cụ lập và luận giải lá số Tử Vi Đẩu Số theo trường phái Khâm Thiên Tứ Hóa Bắc Phái miễn phí",
        "applicationCategory" => "UtilitiesApplication",
        "operatingSystem" => "Web",
        "inLanguage" => "vi",
        "isAccessibleForFree" => true,
        "offers" => ["@type" => "Offer","price" => "0","priceCurrency" => "VND"],
        "author" => ["@type" => "Person","name" => "Chiến Nguyễn","url" => "https://khamthientuhoa.com"],
        "publisher" => ["@type" => "Organization","name" => "Khâm Thiên Tứ Hóa Việt Nam","url" => "https://khamthientuhoa.com"]
    ],
    [
        "@context" => "https://schema.org",
        "@type" => "Organization",
        "name" => "Khâm Thiên Tứ Hóa Việt Nam",
        "url" => "https://khamthientuhoa.com",
        "sameAs" => ["https://www.facebook.com/chiennguyen.2612","https://www.youtube.com/@tuvidauso"],
        "description" => "Nền tảng kiến thức Tử Vi Đẩu Số theo trường phái Khâm Thiên Tứ Hóa Bắc Phái chính thống",
        "contactPoint" => ["@type" => "ContactPoint","contactType" => "customer service","url" => "https://www.facebook.com/messages/t/1333700451"]
    ]
];
?>
<script type="application/ld+json">
<?php echo json_encode($schema, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); ?>
</script>
<style>
/* ===== RESET ===== */
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}

/* ========= THEME VARIABLES ========= */

/* --- TỐI (Dark gold) --- */
[data-theme="dark"]{
  --bg:       #0a0807;
  --bg2:      #110f0c;
  --bg3:      #1a1610;
  --accent:   #c9a84c;
  --accent2:  #e8c86e;
  --accent3:  #f5dfa0;
  --text:     #e8dcc8;
  --text2:    #b8a898;
  --text3:    #7a6a58;
  --border:   rgba(201,168,76,.18);
  --border2:  rgba(201,168,76,.35);
  --shadow:   0 4px 24px rgba(0,0,0,.6);
  --shadow2:  0 2px 12px rgba(0,0,0,.4);
  --good-bg:  rgba(39,174,96,.08);
  --good-bd:  #2ecc71;
  --good-tx:  #5dde92;
  --bad-bg:   rgba(192,57,43,.08);
  --bad-bd:   #e74c3c;
  --bad-tx:   #f08070;
  --mix-bg:   rgba(150,80,180,.07);
  --mix-bd:   #b06fd0;
  --mix-tx:   #cc99e8;
  --neu-bg:   rgba(255,255,255,.02);
  --neu-tx:   #b8a898;
  --btn-tx:   #0a0807;
}

/* --- SÁNG (Light) --- */
[data-theme="light"]{
  --bg:       #f8f6f1;
  --bg2:      #ffffff;
  --bg3:      #f0ece2;
  --accent:   #8b6914;
  --accent2:  #a07820;
  --accent3:  #6b5010;
  --text:     #2d2416;
  --text2:    #5a4a30;
  --text3:    #9a8060;
  --border:   rgba(139,105,20,.18);
  --border2:  rgba(139,105,20,.35);
  --shadow:   0 4px 24px rgba(0,0,0,.1);
  --shadow2:  0 2px 12px rgba(0,0,0,.06);
  --good-bg:  rgba(39,174,96,.08);
  --good-bd:  #27ae60;
  --good-tx:  #1e7a44;
  --bad-bg:   rgba(192,57,43,.07);
  --bad-bd:   #c0392b;
  --bad-tx:   #962c21;
  --mix-bg:   rgba(120,50,160,.06);
  --mix-bd:   #8e44ad;
  --mix-tx:   #6c3483;
  --neu-bg:   rgba(0,0,0,.025);
  --neu-tx:   #5a4a30;
  --btn-tx:   #ffffff;
}

/* --- XANH (Blue/Indigo) --- */
[data-theme="blue"]{
  --bg:       #0b0f1a;
  --bg2:      #111827;
  --bg3:      #1c2538;
  --accent:   #60a5fa;
  --accent2:  #93c5fd;
  --accent3:  #bfdbfe;
  --text:     #e2e8f0;
  --text2:    #94a3b8;
  --text3:    #4a5568;
  --border:   rgba(96,165,250,.18);
  --border2:  rgba(96,165,250,.35);
  --shadow:   0 4px 24px rgba(0,0,0,.6);
  --shadow2:  0 2px 12px rgba(0,0,0,.4);
  --good-bg:  rgba(16,185,129,.08);
  --good-bd:  #10b981;
  --good-tx:  #34d399;
  --bad-bg:   rgba(239,68,68,.08);
  --bad-bd:   #ef4444;
  --bad-tx:   #f87171;
  --mix-bg:   rgba(139,92,246,.08);
  --mix-bd:   #8b5cf6;
  --mix-tx:   #a78bfa;
  --neu-bg:   rgba(255,255,255,.02);
  --neu-tx:   #94a3b8;
  --btn-tx:   #0b0f1a;
}

/* --- TRÀ (Warm tea/zen) --- */
[data-theme="tea"]{
  --bg:       #faf7f2;
  --bg2:      #ffffff;
  --bg3:      #f2ece0;
  --accent:   #6d4c2a;
  --accent2:  #8b5e35;
  --accent3:  #4a3018;
  --text:     #2c1f0e;
  --text2:    #6b4c2a;
  --text3:    #a07850;
  --border:   rgba(109,76,42,.18);
  --border2:  rgba(109,76,42,.32);
  --shadow:   0 4px 24px rgba(0,0,0,.08);
  --shadow2:  0 2px 12px rgba(0,0,0,.05);
  --good-bg:  rgba(56,142,60,.07);
  --good-bd:  #388e3c;
  --good-tx:  #2e7d32;
  --bad-bg:   rgba(183,28,28,.06);
  --bad-bd:   #b71c1c;
  --bad-tx:   #8b0000;
  --mix-bg:   rgba(106,27,154,.06);
  --mix-bd:   #6a1b9a;
  --mix-tx:   #4a148c;
  --neu-bg:   rgba(0,0,0,.03);
  --neu-tx:   #6b4c2a;
  --btn-tx:   #ffffff;
}

html{scroll-behavior:smooth}
body{
  background:var(--bg);
  color:var(--text);
  font-family:'Inter',sans-serif;
  font-size:15px;
  line-height:1.75;
  min-height:100vh;
  transition:background .3s,color .3s;
}

/* ===== THEME SWITCHER ===== */
.theme-bar{
  position:fixed;top:16px;right:16px;z-index:999;
  display:flex;align-items:center;gap:8px;
  background:var(--bg2);border:1px solid var(--border2);
  border-radius:40px;padding:6px 10px;
  box-shadow:var(--shadow2);
  transition:background .3s,border-color .3s;
}
.theme-bar-label{font-size:11px;color:var(--text3);letter-spacing:1px;margin-right:2px;white-space:nowrap}
.theme-btn{
  width:24px;height:24px;border-radius:50%;
  border:2px solid transparent;cursor:pointer;
  transition:transform .2s,border-color .2s;
  outline:none;
}
.theme-btn:hover{transform:scale(1.2)}
.theme-btn.active{border-color:var(--accent2);transform:scale(1.15)}
.theme-btn[data-t="dark"] {background:linear-gradient(135deg,#0a0807,#c9a84c)}
.theme-btn[data-t="light"]{background:linear-gradient(135deg,#f8f6f1,#a07820)}
.theme-btn[data-t="blue"] {background:linear-gradient(135deg,#0b0f1a,#60a5fa)}
.theme-btn[data-t="tea"]  {background:linear-gradient(135deg,#faf7f2,#6d4c2a)}

/* ===== LAYOUT ===== */
.wrap{max-width:900px;margin:0 auto;padding:24px 16px 60px}
/* ===== HEADER ===== */
.site-header{text-align:center;padding:56px 0 36px;position:relative;}
.site-header::after{content:'';display:block;width:120px;height:1px;background:linear-gradient(90deg,transparent,var(--accent),transparent);margin:24px auto 0;}
.ornament{color:var(--accent);font-size:12px;letter-spacing:6px;margin-bottom:12px;opacity:.7}
.site-title{font-family:'Playfair Display',serif;font-size:clamp(24px,5vw,38px);font-weight:700;background:linear-gradient(135deg,var(--accent2),var(--accent3),var(--accent));-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;letter-spacing:1px;}
.site-sub{color:var(--text3);font-size:13px;margin-top:6px;letter-spacing:2px}
/* ===== FORM ===== */
.form-card{background:var(--bg2);border:1px solid var(--border2);border-radius:14px;padding:32px;margin-bottom:40px;box-shadow:var(--shadow);transition:background .3s,border-color .3s;}
.form-card h2{font-family:'Playfair Display',serif;font-size:20px;color:var(--accent2);margin-bottom:24px;display:flex;align-items:center;gap:10px;}
.form-card h2::before{content:'✦';font-size:14px;opacity:.7}
.form-grid{display:grid;grid-template-columns:1fr 1fr;gap:18px}
@media(max-width:580px){.form-grid{grid-template-columns:1fr}}
.field label{display:block;font-size:12px;font-weight:600;color:var(--accent);letter-spacing:1px;text-transform:uppercase;margin-bottom:8px;}
.field input,.field select{width:100%;background:var(--bg3);border:1px solid var(--border2);border-radius:8px;color:var(--text);font-size:14px;padding:12px 14px;outline:none;transition:border-color .2s,box-shadow .2s;appearance:none;-webkit-appearance:none;}
.field input:focus,.field select:focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(128,128,128,.15);}
.field select option{background:var(--bg3);color:var(--text)}
.btn-submit{width:100%;background:linear-gradient(135deg,var(--accent3),var(--accent),var(--accent2));color:var(--btn-tx);font-weight:700;font-size:15px;border:none;border-radius:8px;padding:14px;cursor:pointer;letter-spacing:.5px;transition:opacity .2s,transform .1s;margin-top:6px;}
.btn-submit:hover{opacity:.9;transform:translateY(-1px)}
.btn-submit:active{transform:translateY(0)}
/* ===== ALERT ===== */
.alert{border-radius:8px;padding:14px 18px;margin-bottom:24px;font-size:14px;border:1px solid;}
.alert-error{background:var(--bad-bg);border-color:var(--bad-bd);color:var(--bad-tx)}
.alert-info{background:var(--good-bg);border-color:var(--border2);color:var(--accent2)}
/* ===== BIRTH BANNER ===== */
.birth-banner{background:rgba(128,128,128,.04);border:1px solid var(--border2);border-radius:14px;padding:24px 28px;margin-bottom:32px;display:flex;flex-wrap:wrap;gap:20px;align-items:center;transition:background .3s,border-color .3s;}
.birth-banner .icon-big{font-size:38px;opacity:.4;line-height:1;color:var(--accent)}
.birth-grid{display:flex;flex-wrap:wrap;gap:16px 32px;flex:1}
.birth-item{display:flex;flex-direction:column;gap:2px}
.birth-item .lbl{font-size:11px;color:var(--text3);letter-spacing:1px;text-transform:uppercase}
.birth-item .val{font-size:16px;color:var(--accent2);font-weight:600}
.source-link{font-size:12px;color:var(--text3);margin-top:16px;word-break:break-all;}
.source-link a{color:var(--accent);text-decoration:none}
.source-link a:hover{text-decoration:underline}
/* ===== TOC ===== */
.toc{background:var(--bg2);border:1px solid var(--border);border-radius:14px;padding:20px 24px;margin-bottom:32px;transition:background .3s;}
.toc-title{font-size:12px;color:var(--accent);letter-spacing:2px;text-transform:uppercase;margin-bottom:14px}
.toc-list{list-style:none;display:flex;flex-direction:column;gap:6px}
.toc-list a{color:var(--text2);font-size:13px;text-decoration:none;display:flex;align-items:center;gap:8px;padding:4px 0;transition:color .15s;}
.toc-list a:hover{color:var(--accent2)}
.toc-list a .toc-icon{color:var(--accent);opacity:.6;font-size:11px;width:14px;text-align:center}
/* ===== SECTION CARDS ===== */
.section-card{background:var(--bg2);border:1px solid var(--border);border-radius:14px;margin-bottom:20px;overflow:hidden;box-shadow:var(--shadow2);transition:border-color .2s,background .3s;}
.section-card:hover{border-color:var(--border2)}
.section-head{display:flex;align-items:center;gap:12px;padding:18px 22px;cursor:pointer;background:var(--bg3);border-bottom:1px solid var(--border);user-select:none;transition:filter .15s;}
.section-head:hover{filter:brightness(1.04)}
.section-icon{width:32px;height:32px;border-radius:50%;background:rgba(128,128,128,.12);display:flex;align-items:center;justify-content:center;color:var(--accent);font-size:14px;flex-shrink:0;}
.section-title{flex:1;font-family:'Playfair Display',serif;font-size:16px;color:var(--text);font-weight:600;}
.section-badge{font-size:10px;padding:3px 8px;border-radius:20px;background:rgba(128,128,128,.1);color:var(--accent);border:1px solid var(--border);letter-spacing:.5px;}
.section-chevron{color:var(--text3);font-size:12px;transition:transform .25s}
.section-card.open .section-chevron{transform:rotate(180deg)}
.section-body{padding:20px 22px;display:none;border-top:1px solid var(--border);}
.section-card.open .section-body{display:block}
/* ===== LINES ===== */
.line-good,.line-bad,.line-neutral,.line-mixed{font-size:14px;line-height:1.8;margin-bottom:8px;padding:8px 12px;border-radius:6px;border-left:3px solid;}
.line-good  {background:var(--good-bg);border-color:var(--good-bd);color:var(--good-tx)}
.line-bad   {background:var(--bad-bg); border-color:var(--bad-bd); color:var(--bad-tx)}
.line-mixed {background:var(--mix-bg); border-color:var(--mix-bd); color:var(--mix-tx)}
.line-neutral{background:var(--neu-bg);border-color:var(--border);color:var(--neu-tx)}
.year{font-weight:700;color:var(--accent2);background:rgba(128,128,128,.1);padding:1px 5px;border-radius:3px}
.age{font-size:12px;color:var(--text3);font-style:italic}
.dv{font-weight:600;color:var(--accent);font-size:13px}
.month-good{color:var(--good-tx);font-size:13px}
.month-bad{color:var(--bad-tx);font-size:13px}
/* ===== REPORT TITLE ===== */
.report-title{font-family:'Playfair Display',serif;font-size:clamp(18px,4vw,26px);color:var(--accent2);text-align:center;margin-bottom:8px;}
.report-sub{text-align:center;color:var(--text3);font-size:13px;margin-bottom:32px}
.divider{width:80px;height:1px;background:linear-gradient(90deg,transparent,var(--accent),transparent);margin:0 auto 32px;}
/* ===== LÁ SỐ IMAGE ===== */
.laso-img-wrap{text-align:center;margin:32px 0;}
.laso-img-wrap img{max-width:100%;border:2px solid var(--border2);border-radius:14px;box-shadow:0 4px 32px rgba(0,0,0,.18);transition:border-color .3s;}
.laso-img-caption{font-size:12px;color:var(--text3);margin-top:10px;letter-spacing:1px;}
/* ===== MODAL OVERLAY ===== */
.reg-overlay{
  position:fixed;inset:0;z-index:1000;
  background:rgba(0,0,0,.55);backdrop-filter:blur(4px);
  display:flex;align-items:center;justify-content:center;padding:16px;
  opacity:0;pointer-events:none;transition:opacity .3s;
}
.reg-overlay.show{opacity:1;pointer-events:all}
.reg-modal{
  background:var(--bg2);border:1px solid var(--border2);
  border-radius:20px;padding:40px 36px 32px;
  max-width:460px;width:100%;position:relative;
  box-shadow:0 20px 60px rgba(0,0,0,.4);
  transform:translateY(24px) scale(.97);
  transition:transform .35s cubic-bezier(.34,1.56,.64,1),background .3s;
}
.reg-overlay.show .reg-modal{transform:translateY(0) scale(1)}
.reg-modal .reg-icon{font-size:40px;text-align:center;margin-bottom:14px}
.reg-modal h2{
  font-family:'Playfair Display',serif;font-size:22px;
  color:var(--accent2);text-align:center;margin-bottom:10px;
}
.reg-modal p{color:var(--text2);font-size:14px;line-height:1.75;text-align:center;margin-bottom:24px;}
.reg-form{display:flex;flex-direction:column;gap:11px}
.reg-form input{
  width:100%;padding:13px 16px;
  background:var(--bg3);border:1px solid var(--border2);
  border-radius:10px;color:var(--text);font-size:14px;outline:none;
  transition:border-color .2s,box-shadow .2s;
}
.reg-form input:focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(128,128,128,.12)}
.reg-form input::placeholder{color:var(--text3)}
.reg-btn{
  background:linear-gradient(135deg,var(--accent3),var(--accent),var(--accent2));
  color:var(--btn-tx);font-weight:700;font-size:15px;
  border:none;border-radius:10px;padding:14px;cursor:pointer;
  transition:opacity .2s,transform .1s;margin-top:2px;
}
.reg-btn:hover{opacity:.9;transform:translateY(-1px)}
.reg-btn:disabled{opacity:.6;cursor:not-allowed;transform:none}
.reg-msg{margin-top:12px;padding:11px 16px;border-radius:8px;font-size:14px;display:none}
.reg-msg.ok {background:var(--good-bg);color:var(--good-tx);border:1px solid var(--good-bd);display:block}
.reg-msg.err{background:var(--bad-bg); color:var(--bad-tx); border:1px solid var(--bad-bd); display:block}
.reg-note{font-size:12px;color:var(--text3);text-align:center;margin-top:12px}
.reg-close{
  position:absolute;top:14px;right:16px;
  background:none;border:none;cursor:pointer;
  color:var(--text3);font-size:20px;line-height:1;
  padding:4px 8px;border-radius:6px;
  transition:background .15s,color .15s;
}
.reg-close:hover{background:rgba(128,128,128,.12);color:var(--text)}
/* Nút mở lại modal (floating) */
.reg-float-btn{
  position:fixed;bottom:24px;right:24px;z-index:900;
  background:linear-gradient(135deg,var(--accent),var(--accent2));
  color:var(--btn-tx);border:none;border-radius:50px;
  padding:12px 18px;font-size:13px;font-weight:600;cursor:pointer;
  box-shadow:0 4px 16px rgba(0,0,0,.25);
  transition:opacity .2s,transform .15s;
  display:none;
}
.reg-float-btn:hover{transform:translateY(-2px);opacity:.95}
/* ===== BOOKS SECTION ===== */
.books-section{margin-top:48px}
.books-title{font-family:'Playfair Display',serif;font-size:18px;color:var(--accent2);text-align:center;margin-bottom:16px;}
.books-panel iframe{width:100%;min-height:600px;border:1px solid var(--border2);border-radius:14px;background:var(--bg2);display:block;}
/* ===== TEACHER SECTION ===== */
.teacher-section{margin-top:32px;margin-bottom:8px}
.teacher-card{
  background:var(--bg2);border:1px solid var(--border2);
  border-radius:16px;padding:28px 28px 24px;
  transition:background .3s,border-color .3s;
}
.teacher-header{display:flex;align-items:center;gap:18px;margin-bottom:20px}
.teacher-avatar{
  width:64px;height:64px;border-radius:50%;flex-shrink:0;
  background:linear-gradient(135deg,var(--accent3),var(--accent));
  display:flex;align-items:center;justify-content:center;
  font-size:28px;color:var(--btn-tx);font-weight:700;
  border:2px solid var(--border2);
}
.teacher-info h3{
  font-family:'Playfair Display',serif;
  font-size:18px;color:var(--accent2);margin-bottom:4px;
}
.teacher-info p{font-size:13px;color:var(--text3);line-height:1.5}
.teacher-bio{
  font-size:14px;color:var(--text2);line-height:1.8;
  margin-bottom:20px;padding-bottom:20px;
  border-bottom:1px solid var(--border);
}
.teacher-groups{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:16px}
@media(max-width:540px){.teacher-groups{grid-template-columns:1fr}}
.teacher-link{
  display:flex;align-items:center;gap:10px;
  padding:11px 14px;border-radius:10px;
  background:var(--bg3);border:1px solid var(--border);
  color:var(--text2);text-decoration:none;font-size:13px;
  transition:border-color .2s,color .15s,background .15s;
}
.teacher-link:hover{border-color:var(--border2);color:var(--accent2);background:var(--bg2)}
.teacher-link .tl-icon{
  width:32px;height:32px;border-radius:8px;flex-shrink:0;
  display:flex;align-items:center;justify-content:center;
  font-size:16px;
}
.tl-icon.fb  {background:rgba(24,119,242,.12);color:#1877f2}
.tl-icon.zalo{background:rgba(0,100,255,.1);color:#0064ff}
.tl-icon.yt  {background:rgba(255,0,0,.1);color:#ff0000}
.tl-icon.web {background:rgba(128,128,128,.1);color:var(--accent)}
.tl-icon.msg {background:rgba(0,153,255,.1);color:#0099ff}
.teacher-link .tl-text{display:flex;flex-direction:column;gap:1px;min-width:0}
.teacher-link .tl-name{font-weight:500;color:var(--text);font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.teacher-link .tl-sub{font-size:11px;color:var(--text3)}
.teacher-contact{
  display:flex;gap:8px;flex-wrap:wrap;padding-top:4px;
}
.tc-btn{
  display:inline-flex;align-items:center;gap:7px;
  padding:9px 16px;border-radius:8px;font-size:13px;font-weight:600;
  text-decoration:none;transition:opacity .2s,transform .1s;
  border:1px solid transparent;
}
.tc-btn:hover{opacity:.88;transform:translateY(-1px)}
.tc-btn.fb  {background:#1877f2;color:#fff}
.tc-btn.zalo{background:#0064ff;color:#fff}
.tc-btn.msg {background:linear-gradient(135deg,#0099ff,#a033ff);color:#fff}

/* ===== RESOURCES ===== */
.resources-section{margin-top:48px;padding-top:32px;border-top:1px solid var(--border)}
.resources-title{font-size:12px;color:var(--text3);letter-spacing:2px;text-transform:uppercase;text-align:center;margin-bottom:16px;}
.resource-links{display:flex;flex-direction:column;gap:8px}
.resource-link{
  display:flex;align-items:center;gap:12px;
  padding:12px 16px;border-radius:10px;
  background:var(--bg2);border:1px solid var(--border);
  color:var(--text2);text-decoration:none;font-size:14px;
  transition:border-color .2s,color .2s,background .2s;
}
.resource-link:hover{border-color:var(--border2);color:var(--accent2);background:var(--bg3)}
.resource-link i{width:18px;text-align:center;color:var(--accent);font-size:15px;flex-shrink:0}

/* ===== FOOTER ===== */
.footer{text-align:center;color:var(--text3);font-size:12px;margin-top:60px;padding-top:24px;border-top:1px solid var(--border)}
@keyframes spin{to{transform:rotate(360deg)}}
@keyframes fadeOut{from{opacity:1;transform:scaleY(1)}to{opacity:0;transform:scaleY(.95)}}
</style>
</head>
<body>

<!-- THEME SWITCHER -->
<div class="theme-bar" title="Chọn giao diện">
  <span class="theme-bar-label">Giao diện</span>
  <button class="theme-btn" data-t="dark"  title="Tối (Vàng đen)"></button>
  <button class="theme-btn" data-t="light" title="Sáng (Vàng trắng)"></button>
  <button class="theme-btn" data-t="blue"  title="Xanh đêm"></button>
  <button class="theme-btn" data-t="tea"   title="Trà nâu"></button>
</div>

<div class="wrap">

  <!-- HEADER -->
  <header class="site-header">
    <div class="ornament">✦ &nbsp; T Ứ &nbsp; H Ó A &nbsp; ✦</div>
    <p class="site-title">Khâm Thiên Tứ Hóa</p>
    <p class="site-sub">Luận Giải Lá Số Miễn Phí</p>
  </header>

  <!-- FORM -->
  <div class="form-card">
    <h2>Nhập thông tin để lập lá số</h2>
    <form method="POST" action="">
      <div class="form-grid">
        <div class="field">
          <label for="date">Ngày sinh dương lịch</label>
          <input type="date" id="date" name="date" required
            value="<?= htmlspecialchars($_POST['date'] ?? '') ?>">
        </div>
        <div class="field">
          <label for="time">Giờ sinh</label>
          <select id="time" name="time" required>
            <option value="" disabled <?= empty($_POST['time']) ? 'selected' : '' ?>>Chọn giờ sinh</option>
            <?php
            $gioOpts = [
              '0'=>'0 giờ (Tý sớm)','1'=>'1 giờ','2'=>'2 giờ (Sửu)','3'=>'3 giờ',
              '4'=>'4 giờ (Dần)','5'=>'5 giờ','6'=>'6 giờ (Mão)','7'=>'7 giờ',
              '8'=>'8 giờ (Thìn)','9'=>'9 giờ','10'=>'10 giờ (Tỵ)','11'=>'11 giờ',
              '12'=>'12 giờ (Ngọ)','13'=>'13 giờ','14'=>'14 giờ (Mùi)','15'=>'15 giờ',
              '16'=>'16 giờ (Thân)','17'=>'17 giờ','18'=>'18 giờ (Dậu)','19'=>'19 giờ',
              '20'=>'20 giờ (Tuất)','21'=>'21 giờ','22'=>'22 giờ (Hợi)','23'=>'23 giờ',
            ];
            foreach ($gioOpts as $v => $lbl) {
              $sel = (isset($_POST['time']) && $_POST['time'] == $v) ? 'selected' : '';
              echo "<option value=\"{$v}\" {$sel}>{$lbl}</option>";
            }
            ?>
          </select>
        </div>
        <div class="field">
          <label for="gender">Giới tính</label>
          <select id="gender" name="gender" required>
            <option value="" disabled <?= empty($_POST['gender']) ? 'selected' : '' ?>>Chọn giới tính</option>
            <option value="1" <?= (($_POST['gender'] ?? '') == '1') ? 'selected' : '' ?>>Nam</option>
            <option value="2" <?= (($_POST['gender'] ?? '') == '2') ? 'selected' : '' ?>>Nữ</option>
          </select>
        </div>
        <div class="field" style="display:flex;align-items:flex-end">
          <button type="submit" class="btn-submit">✦ &nbsp; Lập lá số &amp; Luận giải</button>
        </div>
      </div>
    </form>
  </div>

  <!-- SEO INTRO -->
  <section class="seo-intro" style="max-width:800px; margin:0 auto 2rem; padding:1.5rem; background:rgba(255,255,255,0.05); border-radius:12px; color:inherit;">
    <h1 style="font-size:1.6rem; margin-bottom:1rem; text-align:center;">
      Lập Lá Số Tử Vi &amp; Luận Giải Miễn Phí
      <br><small style="font-size:0.9rem; opacity:0.8;">Theo trường phái Khâm Thiên Tứ Hóa Bắc Phái chính thống</small>
    </h1>
    <p style="text-align:center; line-height:1.7;">
      Công cụ lập lá số Tử Vi Đẩu Số theo hệ thống <strong>Khâm Thiên Tứ Hóa</strong> — trường phái Bắc Phái chính thống do Thầy Chiến Nguyễn nghiên cứu và phát triển tại Việt Nam. Nhập ngày sinh, giờ sinh và giới tính để nhận bản luận giải lá số chuyên sâu hoàn toàn miễn phí.
    </p>
  </section>

  <!-- GIỚI THIỆU THẦY CHIẾN NGUYỄN -->
  <section class="teacher-section">
    <div class="teacher-card">
      <div class="teacher-header">
        <div class="teacher-avatar">✦</div>
        <div class="teacher-info">
          <h3>Thầy Chiến Nguyễn</h3>
          <p>Chuyên gia Khâm Thiên Tứ Hóa &amp; Hà Lạc Bắc Phái</p>
        </div>
      </div>

      <p class="teacher-bio">
        Thầy Chiến Nguyễn là chuyên gia nghiên cứu và giảng dạy <strong>Khâm Thiên Tứ Hóa và Hà Lạc Bắc Phái</strong> — hai hệ thống chuyên sâu theo trường phái Bắc Phái chính thống. Với phương pháp kết hợp học thuật và thực chiến, thầy đã đào tạo nhiều thế hệ học viên trên khắp Việt Nam. Website <a href="https://khamthientuhoa.com" target="_blank" rel="noopener" style="color:var(--accent)">khamthientuhoa.com</a> cung cấp hơn <strong><?= htmlspecialchars($postCount) ?> bài viết</strong> hoàn toàn miễn phí.
      </p>

      <!-- Các nhóm & cộng đồng -->
      <div class="teacher-groups">
        <a class="teacher-link" href="https://www.facebook.com/KhamThienTuHoaVietNam" target="_blank" rel="noopener">
          <div class="tl-icon fb"><i class="fa-brands fa-facebook-f"></i></div>
          <div class="tl-text">
            <span class="tl-name">Khâm Thiên Tứ Hóa Việt Nam</span>
            <span class="tl-sub">Trang chính thức</span>
          </div>
        </a>
        <a class="teacher-link" href="https://www.facebook.com/groups/tuviluangiaimienphi" target="_blank" rel="noopener">
          <div class="tl-icon fb"><i class="fa-brands fa-facebook-f"></i></div>
          <div class="tl-text">
            <span class="tl-name">Luận giải Tử Vi miễn phí</span>
            <span class="tl-sub">Nhóm Facebook</span>
          </div>
        </a>
        <a class="teacher-link" href="https://www.facebook.com/groups/452638708403528/" target="_blank" rel="noopener">
          <div class="tl-icon fb"><i class="fa-brands fa-facebook-f"></i></div>
          <div class="tl-text">
            <span class="tl-name">Nhóm Sách Huyền Học</span>
            <span class="tl-sub">Nhóm Facebook</span>
          </div>
        </a>
        <a class="teacher-link" href="https://zalo.me/g/hgtgml669" target="_blank" rel="noopener">
          <div class="tl-icon zalo">Z</div>
          <div class="tl-text">
            <span class="tl-name">Cộng Đồng Tứ Hóa Bắc Phái</span>
            <span class="tl-sub">Nhóm Zalo miễn phí</span>
          </div>
        </a>
        <a class="teacher-link" href="https://zalo.me/g/ytmnwz677" target="_blank" rel="noopener">
          <div class="tl-icon zalo">Z</div>
          <div class="tl-text">
            <span class="tl-name">Tứ Hóa Thực Chiến Sơ Cấp</span>
            <span class="tl-sub">Lớp học Zalo miễn phí</span>
          </div>
        </a>
        <a class="teacher-link" href="https://www.youtube.com/@tuvidauso" target="_blank" rel="noopener">
          <div class="tl-icon yt"><i class="fa-brands fa-youtube"></i></div>
          <div class="tl-text">
            <span class="tl-name">Kênh YouTube Tứ Hóa</span>
            <span class="tl-sub">Video khóa học miễn phí</span>
          </div>
        </a>
        <a class="teacher-link" href="https://khamthientuhoa.com" target="_blank" rel="noopener">
          <div class="tl-icon web"><i class="fa-solid fa-globe"></i></div>
          <div class="tl-text">
            <span class="tl-name">khamthientuhoa.com</span>
            <span class="tl-sub"><?= htmlspecialchars($postCount) ?> bài viết miễn phí</span>
          </div>
        </a>
      </div>

      <!-- Liên hệ trực tiếp -->
      <div class="teacher-contact">
        <a class="tc-btn fb" href="https://www.facebook.com/chiennguyen.2612" target="_blank" rel="noopener">
          <i class="fa-brands fa-facebook-f"></i> Facebook thầy Chiến
        </a>
        <a class="tc-btn msg" href="https://www.facebook.com/messages/t/1333700451" target="_blank" rel="noopener">
          <i class="fa-brands fa-facebook-messenger"></i> Nhắn tin Messenger
        </a>
        <a class="tc-btn zalo" href="https://zalo.me/0946886286" target="_blank" rel="noopener">
          <span style="font-weight:800;font-size:14px">Z</span> Zalo: 0946.886.286
        </a>
      </div>
    </div>
  </section>

  <?php if ($error): ?>
    <div class="alert alert-error"><?= htmlspecialchars($error) ?></div>
  <?php endif; ?>

  <?php if ($result !== null && !$error): ?>

    <!-- BIRTH INFO -->
    <div class="birth-banner">
      <div class="icon-big">☯</div>
      <div class="birth-grid">
        <?php foreach ($birthInfo as $lbl => $val): ?>
          <div class="birth-item">
            <span class="lbl"><?= $lbl ?></span>
            <span class="val"><?= htmlspecialchars($val) ?></span>
          </div>
        <?php endforeach; ?>
      </div>
    </div>

    <!-- ẢNH LÁ SỐ -->
    <?php if (!empty($imageUrl)): ?>
    <div class="laso-img-wrap">
      <img src="<?= htmlspecialchars($imageUrl) ?>" alt="Lá số Tứ Hóa" loading="lazy">
      <p class="laso-img-caption">✦ Lá Số Tứ Hóa ✦</p>
    </div>
    <?php endif; ?>

    <?php if (!empty($result)): ?>

    <!-- REPORT TITLE -->
    <div style="margin-top:36px">
      <h2 class="report-title">Luận Giải Lá Số Miễn Phí</h2>
      <p class="report-sub">Phân tích theo phương pháp Tứ Hóa — Khâm Thiên</p>
      <div class="divider"></div>
    </div>

    <!-- TABLE OF CONTENTS -->
    <?php
    $tocSections = array_filter($result, fn($s) => $s['type'] !== 'info' && !empty($s['content']));
    if (count($tocSections) > 3):
    ?>
    <div class="toc">
      <div class="toc-title">Mục lục</div>
      <ul class="toc-list">
        <?php foreach ($tocSections as $i => $sec): ?>
          <li>
            <a href="#sec-<?= $sec['idx'] ?? $i ?>">
              <span class="toc-icon"><?= $typeIcon[$sec['type']] ?? '◆' ?></span>
              <?= htmlspecialchars(mb_substr($sec['title'], 0, 70)) ?>
            </a>
          </li>
        <?php endforeach; ?>
      </ul>
    </div>
    <?php endif; ?>

    <!-- SECTIONS -->
    <?php foreach ($result as $i => $sec):
      if (empty($sec['content'])) continue;
      $icon  = $typeIcon[$sec['type']] ?? '◆';
      $badge = $typeLabel[$sec['type']] ?? '';
      $isOpen = $i === 0 || in_array($sec['type'], ['tongQuan','tongQuanDoi']);
    ?>
    <div class="section-card <?= $isOpen ? 'open' : '' ?>" id="sec-<?= $sec['idx'] ?? $i ?>">
      <div class="section-head" onclick="toggleSection(this)">
        <div class="section-icon"><?= $icon ?></div>
        <div class="section-title"><?= htmlspecialchars(mb_substr($sec['title'], 0, 80)) ?></div>
        <?php if ($badge): ?>
          <span class="section-badge"><?= $badge ?></span>
        <?php endif; ?>
        <span class="section-chevron">▼</span>
      </div>
      <div class="section-body">
        <?php foreach ($sec['content'] as $item):
          if (empty(trim($item['text'] ?? ''))) continue;
          echo renderLine($item);
        endforeach; ?>
      </div>
    </div>
    <?php endforeach; ?>

    <?php else: ?>
      <div class="alert alert-info">Đã tải dữ liệu nhưng không tìm thấy nội dung luận giải. Vui lòng thử lại.</div>
    <?php endif; ?>

  <?php endif; ?>

  <!-- SÁCH GIẢM GIÁ HOT -->
  <section class="books-section" aria-label="Sách giảm giá HOT">
    <h2 class="books-title">✦ Sách Giảm Giá HOT ✦</h2>
    <div class="books-panel">
      <iframe
        src="https://khosachquy.com/products_tiep_thi_cat33.php?embed=1"
        scrolling="auto"
        title="Sách Khâm Thiên Tứ Hóa"
        loading="lazy"
        style="width:100%; border:none;"
      ></iframe>
    </div>
  </section>

  <!-- TÀI NGUYÊN CỘNG ĐỒNG -->
  <section class="resources-section" aria-label="Tài nguyên miễn phí">
    <p class="resources-title">Tài nguyên cộng đồng</p>
    <nav class="resource-links">
      <a class="resource-link" href="https://www.facebook.com/groups/tuviluangiaimienphi" target="_blank" rel="noopener noreferrer">
        <i class="fa-brands fa-facebook-f" aria-hidden="true"></i>
        <span>Các thầy Khâm Thiên Tứ Hóa luận giải lá số miễn phí</span>
      </a>
      <a class="resource-link" href="https://www.youtube.com/@tuvidauso" target="_blank" rel="noopener noreferrer">
        <i class="fa-brands fa-youtube" aria-hidden="true"></i>
        <span>Các khóa học Khâm Thiên Tứ Hóa miễn phí</span>
      </a>
      <a class="resource-link" href="http://khosachquy.com/sach-tu-vi-pdf-mien-phi" target="_blank" rel="noopener noreferrer">
        <i class="fa-solid fa-book" aria-hidden="true"></i>
        <span>Tài liệu Khâm Thiên Tứ Hóa miễn phí</span>
      </a>
      <a class="resource-link" href="https://zalo.me/g/hgtgml669" target="_blank" rel="noopener noreferrer">
        <i class="fa-solid fa-users" aria-hidden="true"></i>
        <span>Cộng Đồng Tứ Hóa Việt Nam</span>
      </a>
      <a class="resource-link" href="https://khamthientuhoa.com/cac-du-an-dich-sach-mien-phi-va-download-sach-mien-phi/" target="_blank" rel="noopener noreferrer">
        <i class="fa-solid fa-cloud-arrow-down" aria-hidden="true"></i>
        <span>Kho Ebook huyền học tiếng Việt số 1</span>
      </a>
      <a class="resource-link" href="https://drive.google.com/drive/u/1/folders/1fRFtcanYdUmC5l0KGtNL6SgWoLha3baD" target="_blank" rel="noopener noreferrer">
        <i class="fa-brands fa-google-drive" aria-hidden="true"></i>
        <span>Kho Ebook huyền học tiếng Việt số 2</span>
      </a>
      <a class="resource-link" href="https://drive.google.com/drive/folders/1i4bXxKUZrMuaRaE0kXHpKEpibFfN9OXn" target="_blank" rel="noopener noreferrer">
        <i class="fa-solid fa-database" aria-hidden="true"></i>
        <span>Kho Ebook huyền học tiếng Trung (~300GB)</span>
      </a>
    </nav>
  </section>

  <footer class="footer">
    <p>© Khâm Thiên Tứ Hóa Việt Nam — Luận giải lá số Tứ Hóa</p>
  </footer>
</div>

<!-- MODAL ĐĂNG KÝ EMAIL -->
<div class="reg-overlay" id="regOverlay">
  <div class="reg-modal">
    <button class="reg-close" id="regClose" title="Đóng — nhắc lại sau 7 ngày">✕</button>
    <div class="reg-icon">📬</div>
    <h2>Nhận Tài Liệu Học Tử Vi Miễn Phí</h2>
    <p>Đăng ký để nhận ngay bộ tài liệu <strong>Khâm Thiên Tứ Hóa</strong> — sách PDF, ebook huyền học, video khóa học miễn phí gửi thẳng vào hộp thư của bạn.</p>
    <div class="reg-form">
      <input type="text"  id="regName"  placeholder="Tên của bạn (không bắt buộc)" maxlength="100">
      <input type="email" id="regEmail" placeholder="Địa chỉ email *">
      <button class="reg-btn" id="regBtn" onclick="submitReg()">✦ &nbsp; Đăng ký nhận tài liệu miễn phí</button>
    </div>
    <div class="reg-msg" id="regMsg"></div>
    <p class="reg-note">🔒 Không spam — không chia sẻ email của bạn</p>
  </div>
</div>

<!-- Nút mở lại modal -->
<button class="reg-float-btn" id="regFloatBtn" onclick="openRegModal()" title="Nhận tài liệu miễn phí">
  📬 Tài liệu miễn phí
</button>

<script>
// ===== THEME =====
const THEMES = ['dark','light','blue','tea'];
const root = document.documentElement;

function applyTheme(t) {
  if (!THEMES.includes(t)) t = 'dark';
  root.setAttribute('data-theme', t);
  document.querySelectorAll('.theme-btn').forEach(b => {
    b.classList.toggle('active', b.dataset.t === t);
  });
  localStorage.setItem('laso-theme', t);
}

document.querySelectorAll('.theme-btn').forEach(btn => {
  btn.addEventListener('click', () => applyTheme(btn.dataset.t));
});

// Load saved theme
applyTheme(localStorage.getItem('laso-theme') || 'light');

// ===== ACCORDION =====
function toggleSection(head) {
  head.closest('.section-card').classList.toggle('open');
}
document.querySelectorAll('.section-card:first-of-type').forEach(c => c.classList.add('open'));

// ===== COOKIE HELPERS =====
function setCookie(name, value, days) {
  const exp = new Date();
  exp.setTime(exp.getTime() + days * 864e5);
  document.cookie = `${name}=${value};expires=${exp.toUTCString()};path=/;SameSite=Lax`;
}
function getCookie(name) {
  return document.cookie.split(';').map(c => c.trim())
    .find(c => c.startsWith(name + '='))?.split('=')[1] ?? null;
}

// ===== MODAL REGISTER =====
function openRegModal() {
  document.getElementById('regOverlay').classList.add('show');
  document.getElementById('regFloatBtn').style.display = 'none';
  document.body.style.overflow = 'hidden';
}
function closeRegModal(saveCookie) {
  const overlay = document.getElementById('regOverlay');
  overlay.classList.remove('show');
  document.body.style.overflow = '';
  if (saveCookie === 'dismiss') {
    setCookie('laso_reg_dismissed', '1', 7);
  }
}

(function initModal() {
  // Đã đăng ký → không hiện lại
  if (getCookie('laso_registered') === '1') return;
  // Đã tắt trong 7 ngày → chỉ hiện nút floating
  if (getCookie('laso_reg_dismissed') === '1') {
    document.getElementById('regFloatBtn').style.display = 'flex';
    return;
  }
  // Lần đầu → hiện sau 4 giây
  setTimeout(openRegModal, 4000);

  // Đóng modal khi bấm nút X
  document.getElementById('regClose')?.addEventListener('click', () => {
    closeRegModal('dismiss');
    // Hiện nút floating để người dùng có thể mở lại
    document.getElementById('regFloatBtn').style.display = 'flex';
  });

  // Đóng modal khi bấm ra ngoài overlay
  document.getElementById('regOverlay')?.addEventListener('click', function(e) {
    if (e.target === this) {
      closeRegModal('dismiss');
      document.getElementById('regFloatBtn').style.display = 'flex';
    }
  });

  // Đóng bằng phím Escape
  document.addEventListener('keydown', e => {
    if (e.key === 'Escape' && document.getElementById('regOverlay').classList.contains('show')) {
      closeRegModal('dismiss');
      document.getElementById('regFloatBtn').style.display = 'flex';
    }
  });
})();

async function submitReg() {
  const btn   = document.getElementById('regBtn');
  const msg   = document.getElementById('regMsg');
  const name  = document.getElementById('regName').value.trim();
  const email = document.getElementById('regEmail').value.trim();

  msg.className = 'reg-msg';

  if (!email || !email.includes('@')) {
    msg.textContent = '⚠ Vui lòng nhập địa chỉ email hợp lệ.';
    msg.className = 'reg-msg err';
    return;
  }

  btn.disabled = true;
  btn.textContent = 'Đang xử lý...';

  try {
    const res  = await fetch('register.php', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({name, email}),
    });
    const data = await res.json();

    if (data.ok || data.dup) {
      msg.innerHTML = '✦ ' + data.msg + '<br><small style="opacity:.85;line-height:1.6;display:block;margin-top:6px">📌 Tài liệu sẽ được gửi qua email. Nếu không thấy trong hộp thư đến, hãy kiểm tra thư mục Quảng cáo hoặc Spam.</small>';
      msg.className = 'reg-msg ok';
      document.getElementById('regName').value  = '';
      document.getElementById('regEmail').value = '';
      btn.textContent = '✓ Thành công!';
      // Cookie vĩnh viễn — không hiện modal lại nữa
      setCookie('laso_registered', '1', 365);
      // Tự đóng modal sau 10 giây
      setTimeout(() => {
        closeRegModal(null);
        document.getElementById('regFloatBtn').style.display = 'none';
      }, 10000);
    } else {
      msg.textContent = '⚠ ' + data.msg;
      msg.className = 'reg-msg err';
      btn.disabled = false;
      btn.textContent = '✦  Đăng ký nhận tài liệu miễn phí';
    }
  } catch(e) {
    msg.textContent = '⚠ Có lỗi xảy ra, vui lòng thử lại.';
    msg.className = 'reg-msg err';
    btn.disabled = false;
    btn.textContent = '✦  Đăng ký nhận tài liệu miễn phí';
  }
}

document.getElementById('regEmail')?.addEventListener('keydown', e => {
  if (e.key === 'Enter') submitReg();
});

// ===== SELECT STYLING =====
document.querySelectorAll('select').forEach(s => {
  const update = () => s.style.color = s.value ? '' : 'var(--text3)';
  s.addEventListener('change', update);
  update();
});
</script>
</body>
</html>
