<?php
require_once 'includes/config.php';

$id_san_pham = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$ma_gioi_thieu = isset($_GET['ref']) ? htmlspecialchars(trim($_GET['ref'])) : '';
$sp = null;
$ds_kho = [];

if ($id_san_pham <= 0) {
    echo "<script>location.href='gian-hang.php';</script>";
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT * FROM san_pham_gian_hang WHERE id = ? AND trang_thai = 'hien_thi'");
    $stmt->execute([$id_san_pham]);
    $sp = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$sp) {
        echo "<script>location.href='gian-hang.php';</script>";
        exit;
    }

    // Lấy thông tin tồn kho theo id sản phẩm
    $stmt_kho = $pdo->prepare("
        SELECT ql.*, sp.ma_hieu, sp.ten_san_pham 
        FROM quan_ly_kho_hang ql 
        JOIN san_pham_gian_hang sp ON ql.id_san_pham = sp.id 
        WHERE ql.id_san_pham = ?
    ");
    $stmt_kho->execute([$id_san_pham]);
    $ds_kho = $stmt_kho->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Lỗi tải sản phẩm.");
}

if (!$sp) {
    echo "<script>location.href='gian-hang.php';</script>";
    exit;
}

$is_affiliate = ((string)($sp['loai_phan_phoi'] ?? 'noi_bo') === 'affiliate');
if ($is_affiliate && !empty($sp['link_affiliate'])) {
    header('Location: ' . $sp['link_affiliate']);
    exit;
}

$has_sale = !empty($sp['gia_khuyen_mai']) && $sp['gia_khuyen_mai'] > 0;
$gia_ban = $has_sale ? (int)$sp['gia_khuyen_mai'] : (int)($sp['gia_ban'] ?: $sp['gia_goc']);
$gia_goc = (int)($sp['gia_goc'] ?: $sp['gia_ban']);
$chiet_khau = $has_sale ? round(($gia_goc - $gia_ban) / $gia_goc * 100) : 0;
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($sp['ten_san_pham']) ?> - Gian Hàng Nghệ Thuật</title>
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: 'Inter', system-ui, sans-serif; background: #f8fafc; color: #1e293b; }
        a { text-decoration: none; color: inherit; }

        .breadcrumb { max-width: 1200px; margin: 0 auto; padding: 18px 24px; font-size: 0.85rem; color: #64748b; }
        .breadcrumb a { color: #2563eb; font-weight: 600; }
        .breadcrumb span { color: #94a3b8; margin: 0 6px; }

        .product-container { max-width: 1200px; margin: 0 auto; padding: 0 24px 48px; }
        
        /* ── LAYOUT 2 CỘT ── */
        .product-main { display: grid; grid-template-columns: 1fr 1fr; gap: 48px; align-items: start; background: #fff; border-radius: 24px; padding: 32px; box-shadow: 0 4px 24px rgba(15,23,42,0.07); }

        /* CỘT TRÁI: ẢNH */
        .gallery-col { display: flex; flex-direction: column; gap: 16px; }
        .main-img-wrap { position: relative; aspect-ratio: 1; border-radius: 20px; overflow: hidden; background: #f1f5f9; }
        .main-img { width: 100%; height: 100%; object-fit: cover; display: block; }
        .main-img-placeholder { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; font-size: 5rem; color: #cbd5e1; }
        
        .thumbnails { display: flex; gap: 12px; overflow-x: auto; padding-bottom: 4px; }
        .thumb { flex-shrink: 0; width: 80px; height: 80px; border-radius: 12px; overflow: hidden; border: 2px solid #e2e8f0; cursor: pointer; transition: border-color .2s, transform .2s; }
        .thumb:hover, .thumb.active { border-color: #2563eb; transform: scale(1.05); }
        .thumb img { width: 100%; height: 100%; object-fit: cover; }

        /* CỘT PHẢI: THÔNG TIN */
        .info-col { display: flex; flex-direction: column; gap: 20px; }
        
        .product-badges { display: flex; gap: 8px; flex-wrap: wrap; }
        .badge-pill { display: inline-flex; align-items: center; gap: 4px; padding: 5px 12px; border-radius: 999px; font-size: 0.75rem; font-weight: 700; }
        .badge-moi { background: #dbeafe; color: #1d4ed8; }
        .badge-hot { background: #fee2e2; color: #b91c1c; }
        .badge-sale { background: #f0fdf4; color: #16a34a; }

        .product-title { font-size: 1.75rem; font-weight: 900; color: #0f172a; line-height: 1.35; }
        .product-sku { font-size: 0.85rem; color: #94a3b8; margin-top: 6px; }

        .price-box { background: linear-gradient(135deg, #f8fafc, #f1f5f9); border-radius: 16px; padding: 20px; }
        .price-row { display: flex; align-items: baseline; gap: 14px; flex-wrap: wrap; }
        .current-price { font-size: 2rem; font-weight: 900; color: #dc2626; }
        .original-price { font-size: 1.1rem; color: #94a3b8; text-decoration: line-through; }
        .discount-pct { background: #dc2626; color: #fff; font-size: 0.8rem; font-weight: 800; padding: 4px 10px; border-radius: 8px; }

        .stock-info { display: flex; align-items: center; gap: 8px; font-size: 0.95rem; color: #16a34a; font-weight: 600; }
        .stock-info.out { color: #dc2626; }

        .action-buttons { display: flex; gap: 14px; margin-top: 8px; }
        .btn-mua-ngay { flex: 1; padding: 16px 24px; border: none; border-radius: 14px; background: linear-gradient(135deg, #2563eb, #1d4ed8); color: #fff; font-size: 1rem; font-weight: 800; cursor: pointer; transition: transform .15s, box-shadow .15s; box-shadow: 0 4px 16px rgba(37,99,235,0.35); }
        .btn-mua-ngay:hover { transform: translateY(-2px); box-shadow: 0 8px 24px rgba(37,99,235,0.45); }
        .btn-lien-he { padding: 16px 24px; border-radius: 14px; background: #fff; border: 2px solid #e2e8f0; color: #475569; font-size: 1rem; font-weight: 700; cursor: pointer; transition: background .15s; }
        .btn-lien-he:hover { background: #f8fafc; }

        .product-meta-list { border-top: 1px solid #e2e8f0; padding-top: 20px; }
        .meta-item { display: flex; gap: 12px; padding: 8px 0; font-size: 0.92rem; color: #475569; }
        .meta-item strong { min-width: 100px; color: #1e293b; }

        /* ── TABS THÔNG TIN CHI TIẾT ── */
        .detail-section { margin-top: 32px; background: #fff; border-radius: 24px; padding: 32px; box-shadow: 0 4px 24px rgba(15,23,42,0.07); }
        
        .tabs-nav { display: flex; gap: 8px; border-bottom: 2px solid #e2e8f0; padding-bottom: 0; margin-bottom: 24px; }
        .tab-btn { padding: 14px 24px; border: none; background: transparent; font-size: 0.95rem; font-weight: 700; color: #64748b; cursor: pointer; border-radius: 10px 10px 0 0; transition: color .2s, background .2s; position: relative; }
        .tab-btn:hover { color: #2563eb; background: #f1f5f9; }
        .tab-btn.active { color: #2563eb; background: #fff; }
        .tab-btn.active::after { content: ''; position: absolute; bottom: -2px; left: 0; right: 0; height: 3px; background: #2563eb; border-radius: 3px 3px 0 0; }

        .tab-content { display: none; font-size: 0.98rem; line-height: 1.8; color: #334155; }
        .tab-content.active { display: block; animation: fadeIn .3s ease; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }

        /* Mô tả */
        .mo-ta-content { line-height: 1.8; color: #334155; }
        .mo-ta-content h2 { font-size: 1.2rem; font-weight: 800; color: #0f172a; margin: 20px 0 10px; }
        .mo-ta-content h3 { font-size: 1.05rem; font-weight: 700; color: #1e293b; margin: 16px 0 8px; }
        .mo-ta-content p { margin: 0 0 12px; }
        .mo-ta-content ul, .mo-ta-content ol { padding-left: 24px; margin: 0 0 12px; }
        .mo-ta-content li { margin-bottom: 6px; }
        .mo-ta-content strong { color: #0f172a; }
        
        /* Thông số kỹ thuật */
        .specs-wrap table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        .specs-wrap table th, .specs-wrap table td { padding: 12px 16px; border: 1px solid #e2e8f0; text-align: left; font-size: 0.95rem; }
        .specs-wrap table th { background: #f8fafc; font-weight: 700; color: #0f172a; width: 35%; }
        .specs-wrap table td { color: #334155; }
        .specs-wrap table tr:nth-child(even) td { background: #f8fafc; }
        .specs-plain { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 12px; }
        .spec-item { display: flex; gap: 12px; padding: 12px; background: #f8fafc; border-radius: 10px; }
        .spec-item strong { min-width: 120px; color: #0f172a; }

        /* Responsive */
        @media (max-width: 900px) {
            .product-main { grid-template-columns: 1fr; gap: 28px; }
            .main-img-wrap { max-height: 400px; }
        }
        @media (max-width: 600px) {
            .product-container { padding: 0 14px 32px; }
            .product-main { padding: 20px; border-radius: 18px; }
            .product-title { font-size: 1.35rem; }
            .current-price { font-size: 1.6rem; }
            .action-buttons { flex-direction: column; }
        }
    </style>
</head>
<body>

<div class="breadcrumb">
    <a href="index.php">Trang chủ</a>
    <span>›</span>
    <a href="gian-hang.php">Gian hàng</a>
    <span>›</span>
    <?= htmlspecialchars($sp['ten_san_pham']) ?>
</div>

<div class="product-container">
    <div class="product-main">
        
        <!-- CỘT TRÁI: ẢNH -->
        <div class="gallery-col">
            <div class="main-img-wrap">
                <?php if (!empty($sp['hinh_anh'])): ?>
                    <img src="<?= htmlspecialchars($sp['hinh_anh']) ?>" alt="<?= htmlspecialchars($sp['ten_san_pham']) ?>" class="main-img" id="mainImg">
                <?php else: ?>
                    <div class="main-img-placeholder">🎵</div>
                <?php endif; ?>
                
                <?php if ($has_sale && $chiet_khau > 0): ?>
                    <div style="position:absolute; top:16px; right:16px; background:#dc2626; color:#fff; font-size:0.85rem; font-weight:800; padding:6px 12px; border-radius:8px;">
                        -<?= $chiet_khau ?>%
                    </div>
                <?php endif; ?>
            </div>
            
            <?php 
            // Nếu có ảnh phụ, hiển thị thumbnails (từ trường hinh_anh_phu dạng JSON)
            $anh_khac = [];
            if (!empty($sp['hinh_anh_phu'])) {
                $anh_khac = json_decode($sp['hinh_anh_phu'], true);
                if (!is_array($anh_khac)) $anh_khac = [];
            }
            if (!empty($anh_khac)): ?>
            <div class="thumbnails">
                <div class="thumb active" onclick="changeImg(this, '<?= htmlspecialchars($sp['hinh_anh']) ?>')">
                    <img src="<?= htmlspecialchars($sp['hinh_anh']) ?>" alt="">
                </div>
                <?php foreach($anh_khac as $anh): $anh = trim($anh); if($anh): ?>
                <div class="thumb" onclick="changeImg(this, '<?= htmlspecialchars($anh) ?>')">
                    <img src="<?= htmlspecialchars($anh) ?>" alt="">
                </div>
                <?php endif; endforeach; ?>
            </div>
            <?php endif; ?>
        </div>

        <!-- CỘT PHẢI: THÔNG TIN -->
        <div class="info-col">
            <div class="product-badges">
                <?php if (!empty($sp['moi'])): ?><span class="badge-pill badge-moi">✨ Hàng mới</span><?php endif; ?>
                <?php if (!empty($sp['noi_bat'])): ?><span class="badge-pill badge-hot">⭐ Nổi bật</span><?php endif; ?>
                <?php if (!empty($sp['ban_chay'])): ?><span class="badge-pill badge-sale">🔥 Bán chạy</span><?php endif; ?>
            </div>

            <h1 class="product-title"><?= htmlspecialchars($sp['ten_san_pham']) ?></h1>
            <?php if (!empty($sp['ma_hieu']) || !empty($ds_kho)): ?>
                <div class="product-sku">
                    <?= !empty($sp['ma_hieu']) ? 'SKU: ' . htmlspecialchars($sp['ma_hieu']) : '' ?>
                    <?php
                    $kho_con_hang = array_filter($ds_kho, fn($k) => (int)$k['so_luong_ton'] > 0);
                    if (!empty($kho_con_hang)):
                    ?>
                        <?= !empty($sp['ma_hieu']) ? '&nbsp;&middot;&nbsp;' : '' ?>📦 <?= implode(', ', array_map(fn($k) => htmlspecialchars($k['vi_tri_kho'] ?? 'Kho chính'), $kho_con_hang)) ?>
                    <?php endif; ?>
                </div>
            <?php endif; ?>

            <div class="price-box">
                <div class="price-row">
                    <span class="current-price"><?= number_format($gia_ban) ?> ₫</span>
                    <?php if ($has_sale): ?>
                        <span class="original-price"><?= number_format($gia_goc) ?> ₫</span>
                    <?php endif; ?>
                </div>
                
                <?php 
                $tong_ton = 0;
                foreach($ds_kho as $k) $tong_ton += (int)$k['so_luong_ton'];
                $co_du_lieu_kho = count($ds_kho) > 0;
                ?>
                <div class="stock-info <?= ($co_du_lieu_kho && $tong_ton == 0) ? 'out' : '' ?>">
                    <?php if (!$co_du_lieu_kho): ?>
                        📞 Liên hệ để biết tình trạng hàng
                    <?php elseif ($tong_ton > 0): ?>
                        ✓ Còn hàng (<?= $tong_ton ?> sản phẩm)
                    <?php else: ?>
                        ✕ Hết hàng
                    <?php endif; ?>
                </div>
            </div>

            <div class="action-buttons">
                <button class="btn-mua-ngay" onclick="datHangNgay()">🛒 Mua ngay</button>
                <button class="btn-lien-he" onclick="location.href='lien-he.php'">📞 Liên hệ</button>
            </div>

            <div class="product-meta-list">
                <?php if (!empty($sp['danh_muc'])): ?>
                <div class="meta-item">
                    <strong>Danh mục:</strong>
                    <span><?= htmlspecialchars($sp['danh_muc']) ?></span>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($ds_kho)): ?>
                <div class="meta-item" style="flex-direction:column; align-items:flex-start; gap:6px;">
                    <strong>Kho hiện có:</strong>
                    <div style="font-size:0.85rem; color:#64748b; display:flex; flex-wrap:wrap; gap:6px;">
                        <?php foreach($ds_kho as $k): ?>
                        <span style="background:#f1f5f9; padding:4px 10px; border-radius:6px;">
                            <?= htmlspecialchars($k['vi_tri_kho'] ?? 'Kho') ?>: <b><?= (int)$k['so_luong_ton'] ?></b>
                        </span>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- TABS THÔNG TIN CHI TIẾT -->
    <div class="detail-section">
        <div class="tabs-nav">
            <button class="tab-btn active" onclick="switchTab('mo-ta', this)">📝 Mô tả sản phẩm</button>
            <button class="tab-btn" onclick="switchTab('thong-so', this)">⚙️ Thông số kỹ thuật</button>
        </div>

        <!-- Tab: Mô tả (lấy từ mo_ta_gian_hang trong thiết lập gian hàng) -->
        <div id="mo-ta" class="tab-content active">
            <?php if (!empty($sp['mo_ta_gian_hang'])): ?>
                <div class="mo-ta-content"><?= $sp['mo_ta_gian_hang'] ?></div>
            <?php else: ?>
                <p style="color:#94a3b8; font-style:italic;">Chưa có mô tả chi tiết cho sản phẩm này.</p>
            <?php endif; ?>
        </div>

        <!-- Tab: Thông số kỹ thuật (lấy từ mo_ta - dạng bảng HTML từ kho) -->
        <div id="thong-so" class="tab-content">
            <?php if (!empty($sp['mo_ta'])): ?>
                <div class="specs-wrap"><?= html_entity_decode($sp['mo_ta'], ENT_QUOTES | ENT_HTML5, 'UTF-8') ?></div>
            <?php else: ?>
                <p style="color:#94a3b8; font-style:italic;">Chưa có thông số kỹ thuật cho sản phẩm này.</p>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Modal Đặt hàng -->
<div id="modalMuaNgay" style="display:none; position:fixed; inset:0; background:rgba(15,23,42,0.65); z-index:9999; align-items:center; justify-content:center;">
    <div style="background:#fff; border-radius:20px; padding:28px; max-width:480px; width:95%; box-shadow:0 24px 60px rgba(15,23,42,0.25);">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:16px;">
            <h3 style="font-size:1.2rem; font-weight:800; color:#0f172a;">🛒 Xác nhận đặt hàng</h3>
            <span onclick="document.getElementById('modalMuaNgay').style.display='none'" style="font-size:28px; font-weight:700; color:#94a3b8; cursor:pointer;">&times;</span>
        </div>
        
        <div style="background:#f8fafc; border-radius:12px; padding:16px; margin-bottom:20px; display:flex; gap:12px;">
            <?php if(!empty($sp['hinh_anh'])): ?>
            <img src="<?= htmlspecialchars($sp['hinh_anh']) ?>" alt="" style="width:70px; height:70px; object-fit:cover; border-radius:8px;">
            <?php endif; ?>
            <div>
                <div style="font-weight:700; color:#0f172a; font-size:0.95rem;"><?= htmlspecialchars($sp['ten_san_pham']) ?></div>
                <div style="color:#dc2626; font-weight:800;"><?= number_format($gia_ban) ?> ₫</div>
                <?php if (!empty($sp['ma_hieu'])): ?>
                <div style="font-size:0.8rem; color:#94a3b8;">SKU: <?= htmlspecialchars($sp['ma_hieu']) ?></div>
                <?php endif; ?>
            </div>
        </div>

        <form action="xu-ly-don-hang.php" method="POST">
            <input type="hidden" name="id_san_pham" value="<?= (int)$sp['id'] ?>">
            <input type="hidden" name="ma_gioi_thieu" value="<?= htmlspecialchars($ma_gioi_thieu) ?>">
            
            <div style="margin-bottom:14px;">
                <label style="display:block; font-size:0.85rem; font-weight:700; color:#475569; margin-bottom:6px;">Số lượng *</label>
                <input type="number" name="so_luong" value="1" min="1" <?= ($co_du_lieu_kho && $tong_ton > 0) ? 'max="'.$tong_ton.'"' : '' ?> required style="width:100%; padding:12px 14px; border:1.5px solid #e2e8f0; border-radius:12px; font-size:0.95rem;">
            </div>
            
            <div style="margin-bottom:14px;">
                <label style="display:block; font-size:0.85rem; font-weight:700; color:#475569; margin-bottom:6px;">Họ và tên người nhận *</label>
                <input type="text" name="ten_khach_hang" required style="width:100%; padding:12px 14px; border:1.5px solid #e2e8f0; border-radius:12px; font-size:0.95rem;">
            </div>
            
            <div style="margin-bottom:14px;">
                <label style="display:block; font-size:0.85rem; font-weight:700; color:#475569; margin-bottom:6px;">Số điện thoại *</label>
                <input type="tel" name="so_dien_thoai" required style="width:100%; padding:12px 14px; border:1.5px solid #e2e8f0; border-radius:12px; font-size:0.95rem;">
            </div>
            
            <div style="margin-bottom:20px;">
                <label style="display:block; font-size:0.85rem; font-weight:700; color:#475569; margin-bottom:6px;">Địa chỉ nhận hàng *</label>
                <input type="text" name="dia_chi" required style="width:100%; padding:12px 14px; border:1.5px solid #e2e8f0; border-radius:12px; font-size:0.95rem;">
            </div>
            
            <button type="submit" style="width:100%; padding:14px; border:none; border-radius:12px; background:linear-gradient(135deg,#2563eb,#1d4ed8); color:#fff; font-weight:800; font-size:1rem; cursor:pointer;">
                ✅ Xác nhận đặt hàng
            </button>
        </form>
    </div>
</div>

<script>
function datHangNgay() {
    document.getElementById('modalMuaNgay').style.display = 'flex';
}

function switchTab(tabId, btn) {
    document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    document.getElementById(tabId).classList.add('active');
    btn.classList.add('active');
}

function changeImg(thumb, src) {
    document.getElementById('mainImg').src = src;
    document.querySelectorAll('.thumb').forEach(t => t.classList.remove('active'));
    thumb.classList.add('active');
}
</script>

    <?php require_once 'includes/menu-dien-thoai.php'; ?>
</body>
</html>