<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

require_once($_SERVER['DOCUMENT_ROOT'] . '/hethong/config.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/hethong/ketnoi.php');

// ============================================================
// KIỂM TRA ĐĂNG NHẬP
// ============================================================
if(!isset($_SESSION['session'])) { 
    header('location: /landing-page'); 
    exit(); 
}

$session = $_SESSION['session'];
$check_user = $ketnoi->query("SELECT * FROM users WHERE session='$session'")->fetch_array();
if(empty($check_user['id'])) { 
    header('location: /landing-page'); 
    exit(); 
}
$user = $check_user;

// ============================================================
// LẤY DANH SÁCH COUPON ĐANG HOẠT ĐỘNG
// ============================================================
$today = date('Y-m-d');
$coupons = $ketnoi->query("
    SELECT * FROM coupons 
    WHERE status = 1 
    AND (expire_date IS NULL OR expire_date >= '$today')
    AND used < max_use
    ORDER BY created_at DESC
");
$totalCoupons = ($coupons) ? $coupons->num_rows : 0;
?>
<!DOCTYPE html>
<html lang="vi" <?php if(isset($_COOKIE['data-bs-theme']) && $_COOKIE['data-bs-theme'] == 'dark') { echo 'data-bs-theme="dark"'; } else { echo 'data-bs-theme="light"'; } ?>>
<head>
    <?php require $_SERVER['DOCUMENT_ROOT'].'/hethong/head2.php';?>
    <title>Mã Giảm Giá | <?=$chinhapi['ten_web'];?></title>
    <?php require $_SERVER['DOCUMENT_ROOT'].'/hethong/nav.php';?>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;600;700;800&display=swap" rel="stylesheet">
    
    <style>
        body { font-family: 'Plus Jakarta Sans', sans-serif; background: #f8fafc; }
        
        .page-header {
            text-align: center;
            margin-bottom: 2rem;
        }
        .page-header h1 {
            font-size: 1.8rem;
            font-weight: 800;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        .page-header p {
            color: #64748b;
            font-size: 0.9rem;
        }
        
        .coupon-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 1.5rem;
            padding: 1rem 0;
        }
        
        .coupon-card {
            background: #ffffff;
            border: 2px dashed #e2e8f0;
            border-radius: 20px;
            padding: 1.5rem;
            position: relative;
            overflow: hidden;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        .coupon-card:hover {
            border-color: #8b5cf6;
            transform: translateY(-5px);
            box-shadow: 0 15px 40px rgba(139, 92, 246, 0.15);
        }
        .coupon-card.used-up {
            opacity: 0.6;
            border-color: #e2e8f0;
            cursor: not-allowed;
        }
        .coupon-card.used-up:hover {
            transform: none;
            box-shadow: none;
        }
        
        .coupon-tag {
            position: absolute;
            top: -10px;
            right: 20px;
            background: linear-gradient(135deg, #8b5cf6, #7c3aed);
            color: #fff;
            padding: 5px 15px;
            border-radius: 0 0 10px 10px;
            font-size: 0.65rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        .coupon-tag.expired {
            background: linear-gradient(135deg, #ef4444, #dc2626);
        }
        
        .coupon-icon {
            width: 55px;
            height: 55px;
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            margin-bottom: 1rem;
        }
        .coupon-icon.percent {
            background: linear-gradient(135deg, #ede9fe, #ddd6fe);
            color: #7c3aed;
        }
        .coupon-icon.fixed {
            background: linear-gradient(135deg, #dbeafe, #bfdbfe);
            color: #3b82f6;
        }
        
        .coupon-code {
            font-family: 'Courier New', monospace;
            font-size: 1.2rem;
            font-weight: 800;
            color: #7c3aed;
            letter-spacing: 2px;
            margin-bottom: 0.5rem;
            word-break: break-all;
        }
        
        .coupon-discount {
            font-size: 2rem;
            font-weight: 900;
            color: #1e293b;
            margin-bottom: 0.3rem;
        }
        .coupon-discount span {
            font-size: 1rem;
            color: #64748b;
        }
        
        .coupon-desc {
            color: #64748b;
            font-size: 0.8rem;
            margin-bottom: 1rem;
            line-height: 1.5;
        }
        
        .coupon-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 0.7rem;
            color: #94a3b8;
            border-top: 1px solid #f1f5f9;
            padding-top: 1rem;
        }
        .coupon-meta i {
            margin-right: 3px;
        }
        
        .coupon-remaining {
            background: #fef3c7;
            color: #d97706;
            padding: 3px 10px;
            border-radius: 20px;
            font-weight: 700;
            font-size: 0.65rem;
        }
        .coupon-remaining.gone {
            background: #fee2e2;
            color: #dc2626;
        }
        
        .copy-btn {
            background: #f1f5f9;
            border: none;
            color: #64748b;
            padding: 8px 15px;
            border-radius: 10px;
            font-size: 0.75rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
            width: 100%;
            margin-top: 0.8rem;
        }
        .copy-btn:hover {
            background: #7c3aed;
            color: #fff;
        }
        .copy-btn.copied {
            background: #059669;
            color: #fff;
        }
        
        .no-coupon {
            text-align: center;
            padding: 4rem 2rem;
            color: #94a3b8;
        }
        .no-coupon i {
            font-size: 4rem;
            display: block;
            margin-bottom: 1rem;
            opacity: 0.3;
        }
        
        @media (max-width: 640px) {
            .coupon-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>

<body id="kt_app_body" data-kt-app-layout="light-sidebar" data-kt-app-header-fixed="true"
    data-kt-app-sidebar-enabled="true" data-kt-app-sidebar-fixed="true" data-kt-app-sidebar-hoverable="true"
    data-kt-app-sidebar-push-header="true" data-kt-app-sidebar-push-toolbar="true"
    data-kt-app-sidebar-push-footer="true" data-kt-app-toolbar-enabled="true" class="app-default">

    <div class="d-flex flex-column flex-root app-root" id="kt_app_root">
        <div class="app-page flex-column flex-column-fluid" id="kt_app_page">
            <div class="app-wrapper flex-column flex-row-fluid" id="kt_app_wrapper">
                <?php require $_SERVER['DOCUMENT_ROOT'].'/hethong/sider.php';?>
                
                <div class="app-main flex-column flex-row-fluid" id="kt_app_main">
                    <div class="d-flex flex-column flex-column-fluid">
                        
                        <div class="content d-flex flex-column flex-column-fluid" id="kt_content">
                            <div class="container-fluid p-6" id="kt_content_container">
                                
                                <div class="page-header">
                                    <h1><i class="fa-solid fa-ticket text-violet me-2"></i>Mã Giảm Giá Hiện Có</h1>
                                    <p>Danh sách mã khuyến mãi đang hoạt động. Nhập mã khi tạo website để được giảm giá!</p>
                                </div>
                                
                                <?php if($coupons && $coupons->num_rows > 0): ?>
                                <div class="coupon-grid">
                                    <?php while($row = $coupons->fetch_assoc()): 
                                        $remaining = $row['max_use'] - $row['used'];
                                        $isExpiring = !empty($row['expire_date']) && strtotime($row['expire_date']) < strtotime('+3 days');
                                        $isGone = $remaining <= 0;
                                    ?>
                                    <div class="coupon-card <?=$isGone ? 'used-up' : '';?>" id="card-<?=$row['id'];?>">
                                        <div class="coupon-tag <?=$isExpiring && !$isGone ? 'expired' : '';?>">
                                            <?php 
                                            if($isGone) echo 'HẾT LƯỢT';
                                            elseif($isExpiring) echo 'SẮP HẾT HẠN';
                                            else echo 'HOT';
                                            ?>
                                        </div>
                                        
                                        <div class="coupon-icon <?=$row['type'];?>">
                                            <?php if($row['type'] == 'percent'): ?>
                                                <i class="fa-solid fa-percent"></i>
                                            <?php else: ?>
                                                <i class="fa-solid fa-coins"></i>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <div class="coupon-code" id="code-<?=$row['id'];?>"><?=htmlspecialchars($row['code']);?></div>
                                        
                                        <div class="coupon-discount">
                                            <?php if($row['type'] == 'percent'): ?>
                                                -<?=$row['discount'];?><span>%</span>
                                            <?php else: ?>
                                                -<?=number_format($row['discount'],0,',','.');?><span>đ</span>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <?php if(!empty($row['description'])): ?>
                                        <div class="coupon-desc"><?=htmlspecialchars($row['description']);?></div>
                                        <?php endif; ?>
                                        
                                        <?php if($row['min_amount'] > 0): ?>
                                        <div class="coupon-desc">
                                            <i class="fa-solid fa-circle-info me-1"></i> Đơn tối thiểu: <?=number_format($row['min_amount'],0,',','.');?>đ
                                        </div>
                                        <?php endif; ?>
                                        
                                        <button class="copy-btn" onclick="copyCode('<?=htmlspecialchars($row['code']);?>', this)" <?=$isGone ? 'disabled' : '';?>>
                                            <i class="fa-regular fa-copy me-1"></i> 
                                            <?=$isGone ? 'Đã hết lượt' : 'Sao chép mã';?>
                                        </button>
                                        
                                        <div class="coupon-meta">
                                            <span>
                                                <i class="fa-regular fa-clock"></i>
                                                <?php if(!empty($row['expire_date'])): ?>
                                                    HSD: <?=date('d/m/Y', strtotime($row['expire_date']));?>
                                                <?php else: ?>
                                                    Không giới hạn
                                                <?php endif; ?>
                                            </span>
                                            <span class="coupon-remaining <?=$isGone ? 'gone' : '';?>">
                                                Còn <?=$remaining;?> lượt
                                            </span>
                                        </div>
                                    </div>
                                    <?php endwhile; ?>
                                </div>
                                <?php else: ?>
                                <div class="no-coupon">
                                    <i class="fa-solid fa-ticket-simple"></i>
                                    <h3 class="fw-bold mb-2">Chưa có mã giảm giá nào</h3>
                                    <p>Vui lòng quay lại sau!</p>
                                </div>
                                <?php endif; ?>
                                
                            </div>
                        </div>
                        
                    </div>
                    <?php require $_SERVER['DOCUMENT_ROOT'].'/hethong/foot.php';?>
                </div>
            </div>
        </div>
    </div>
    
    <script>
    function copyCode(code, btn) {
        navigator.clipboard.writeText(code).then(function() {
            btn.innerHTML = '<i class="fa-solid fa-check me-1"></i> Đã sao chép!';
            btn.classList.add('copied');
            setTimeout(function() {
                btn.innerHTML = '<i class="fa-regular fa-copy me-1"></i> Sao chép mã';
                btn.classList.remove('copied');
            }, 2000);
        }).catch(function() {
            // Fallback cho mobile
            var input = document.createElement('input');
            input.value = code;
            document.body.appendChild(input);
            input.select();
            document.execCommand('copy');
            document.body.removeChild(input);
            
            btn.innerHTML = '<i class="fa-solid fa-check me-1"></i> Đã sao chép!';
            btn.classList.add('copied');
            setTimeout(function() {
                btn.innerHTML = '<i class="fa-regular fa-copy me-1"></i> Sao chép mã';
                btn.classList.remove('copied');
            }, 2000);
        });
    }
    </script>
</body>
</html>