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

require_once('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' ");

if(!$check_user || $check_user->num_rows == 0) { 
    header('location: /landing-page'); 
    exit(); 
}

$user = $check_user->fetch_array();

// ============================================================
// TẠO BẢNG NẾU CHƯA CÓ
// ============================================================

// Bảng coupon
$sql1 = "CREATE TABLE IF NOT EXISTS `coupons` (
  `id` int NOT NULL AUTO_INCREMENT,
  `code` varchar(50) NOT NULL,
  `discount` int NOT NULL DEFAULT 0,
  `type` enum('percent','fixed') NOT NULL DEFAULT 'percent',
  `min_amount` int NOT NULL DEFAULT 0,
  `max_discount` int NOT NULL DEFAULT 0,
  `max_use` int NOT NULL DEFAULT 1,
  `used` int NOT NULL DEFAULT 0,
  `expire_date` date DEFAULT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1,
  `description` varchar(255) DEFAULT NULL,
  `created_at` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `code` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
$ketnoi->query($sql1);

// Bảng lịch sử sử dụng coupon
$sql2 = "CREATE TABLE IF NOT EXISTS `coupon_history` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(100) NOT NULL,
  `code` varchar(50) NOT NULL,
  `discount` int NOT NULL DEFAULT 0,
  `order_amount` int NOT NULL DEFAULT 0,
  `saved_amount` int NOT NULL DEFAULT 0,
  `used_at` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
$ketnoi->query($sql2);

// ============================================================
// XỬ LÝ POST
// ============================================================
$message = '';
$msgType = '';

if($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = isset($_POST['action']) ? $_POST['action'] : '';

    // THÊM COUPON
    if($action === 'add') {
        $code        = isset($_POST['code']) ? strtoupper(trim($_POST['code'])) : '';
        $discount    = isset($_POST['discount']) ? (int)$_POST['discount'] : 0;
        $type        = isset($_POST['type']) ? $_POST['type'] : 'percent';
        $min_amount  = isset($_POST['min_amount']) ? (int)$_POST['min_amount'] : 0;
        $max_discount = isset($_POST['max_discount']) ? (int)$_POST['max_discount'] : 0;
        $max_use     = isset($_POST['max_use']) ? (int)$_POST['max_use'] : 1;
        $expire      = isset($_POST['expire_date']) ? trim($_POST['expire_date']) : '';
        $description = isset($_POST['description']) ? trim($_POST['description']) : '';

        if(empty($code) || $discount <= 0) {
            $message = 'Vui lòng nhập đầy đủ mã và mức giảm giá!';
            $msgType = 'error';
        } else {
            $code = $ketnoi->real_escape_string($code);
            
            // Kiểm tra trùng
            $check = $ketnoi->query("SELECT id FROM `coupons` WHERE `code`='$code'");
            if($check && $check->num_rows > 0) {
                $message = '❌ Mã <b>' . htmlspecialchars($code) . '</b> đã tồn tại!';
                $msgType = 'error';
            } else {
                $expireVal = !empty($expire) ? "'" . $ketnoi->real_escape_string($expire) . "'" : "NULL";
                $descVal = !empty($description) ? "'" . $ketnoi->real_escape_string($description) . "'" : "NULL";
                
                $insert = $ketnoi->query("INSERT INTO `coupons` (`code`,`discount`,`type`,`min_amount`,`max_discount`,`max_use`,`expire_date`,`description`,`status`,`created_at`) VALUES ('$code',$discount,'$type',$min_amount,$max_discount,$max_use,$expireVal,$descVal,1,NOW())");
                
                if($insert) {
                    $message = '✅ Đã thêm mã giảm giá <b>' . htmlspecialchars($code) . '</b> thành công!';
                    $msgType = 'success';
                } else {
                    $message = '❌ Lỗi: ' . $ketnoi->error;
                    $msgType = 'error';
                }
            }
        }
    }

    // XÓA COUPON
    if($action === 'delete') {
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        if($id > 0) {
            $ketnoi->query("DELETE FROM `coupons` WHERE `id`=$id");
            $message = '✅ Đã xóa mã giảm giá!';
            $msgType = 'success';
        }
    }

    // BẬT/TẮT TRẠNG THÁI
    if($action === 'toggle') {
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        if($id > 0) {
            $ketnoi->query("UPDATE `coupons` SET `status` = 1 - `status` WHERE `id`=$id");
            $message = '✅ Đã cập nhật trạng thái!';
            $msgType = 'success';
        }
    }
}

// ============================================================
// LẤY DỮ LIỆU
// ============================================================

// Danh sách coupon
$list = $ketnoi->query("SELECT * FROM `coupons` ORDER BY `id` DESC");
$totalCoupons = ($list) ? $list->num_rows : 0;

// Thống kê
$statsQuery = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status=1 AND (expire_date IS NULL OR expire_date >= CURDATE()) THEN 1 ELSE 0 END) as active,
    SUM(CASE WHEN status=0 THEN 1 ELSE 0 END) as inactive,
    SUM(CASE WHEN expire_date IS NOT NULL AND expire_date < CURDATE() THEN 1 ELSE 0 END) as expired,
    SUM(used) as total_used,
    SUM(max_use) as total_max
FROM `coupons`";
$statsResult = $ketnoi->query($statsQuery);
$stats = ($statsResult) ? $statsResult->fetch_assoc() : [
    'total' => 0, 'active' => 0, 'inactive' => 0, 'expired' => 0,
    'total_used' => 0, 'total_max' => 0
];

// Lịch sử sử dụng
$history = $ketnoi->query("SELECT * FROM `coupon_history` ORDER BY `id` DESC LIMIT 50");
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <?php require_once('hethong/head2.php');?>
    <title>Quản Lý Mã Giảm Giá | Light Pro UI</title>
    <?php require_once('hethong/nav.php');?>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;600;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body { font-family: 'Plus Jakarta Sans', sans-serif; background: #f8fafc; }
        .bento-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 1.5rem; }
        .white-card { 
            background: #ffffff;
            border: 1px solid #e2e8f0;
            border-radius: 24px;
            padding: 24px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
            transition: 0.3s;
        }
        .white-card:hover { transform: translateY(-5px); box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); }
        .stat-val { font-size: 1.8rem; font-weight: 800; color: #1e293b; }
        .table-wrap::-webkit-scrollbar { height: 6px; }
        .table-wrap::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 10px; }
        .table-wrap::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
        input:focus, textarea:focus, select:focus { outline: none; }
    </style>
</head>
<body class="text-slate-800">
    <div class="wrapper">
        <div class="content-wrapper bg-transparent p-6 md:p-10">
            
            <!-- Header -->
            <div class="mb-10 flex flex-wrap items-center justify-between gap-4">
                <div>
                    <h1 class="text-3xl font-extrabold text-slate-900 flex items-center gap-3">
                        <span class="w-10 h-10 bg-violet-100 text-violet-600 rounded-xl flex items-center justify-center">
                            <i class="fas fa-tags text-lg"></i>
                        </span>
                        Quản Lý Mã Giảm Giá
                    </h1>
                    <p class="text-slate-500 mt-1">Tạo & quản lý mã khuyến mãi, giảm giá cho khách hàng</p>
                </div>
                <a href="#formSection" class="bg-violet-600 text-white font-bold text-sm px-6 py-3 rounded-2xl hover:bg-violet-700 transition shadow-lg shadow-violet-200">
                    <i class="fas fa-plus mr-2"></i> Tạo Mã Mới
                </a>
            </div>

            <!-- Stats -->
            <div class="bento-grid mb-8">
                <div class="white-card">
                    <p class="text-slate-500 text-xs font-bold uppercase tracking-wider">🏷️ Tổng Mã</p>
                    <div class="stat-val"><?=number_format($stats['total']);?></div>
                </div>
                <div class="white-card">
                    <p class="text-emerald-600 text-xs font-bold uppercase tracking-wider">✅ Đang Hoạt Động</p>
                    <div class="stat-val text-emerald-600"><?=number_format($stats['active']);?></div>
                </div>
                <div class="white-card">
                    <p class="text-amber-600 text-xs font-bold uppercase tracking-wider">⚠️ Hết Hạn</p>
                    <div class="stat-val text-amber-600"><?=number_format($stats['expired']);?></div>
                </div>
                <div class="white-card">
                    <p class="text-indigo-600 text-xs font-bold uppercase tracking-wider">👥 Tổng Lượt Dùng</p>
                    <div class="stat-val text-indigo-600"><?=number_format($stats['total_used']);?><span class="text-lg text-slate-400 font-medium">/<?=number_format($stats['total_max']);?></span></div>
                </div>
            </div>

            <!-- Message -->
            <?php if($message): ?>
            <div class="mb-6 p-4 rounded-2xl text-sm font-semibold flex items-center gap-3 <?=$msgType=='success' ? 'bg-emerald-50 text-emerald-700 border border-emerald-200' : 'bg-rose-50 text-rose-700 border border-rose-200';?>">
                <i class="fas fa-<?=$msgType=='success'?'circle-check':'circle-exclamation';?> text-lg"></i>
                <span><?=$message;?></span>
            </div>
            <?php endif; ?>

            <!-- Form Tạo Coupon -->
            <div id="formSection" class="white-card mb-8">
                <h2 class="text-lg font-extrabold text-slate-900 mb-6 flex items-center gap-2">
                    <span class="w-1 h-6 bg-violet-600 rounded-full"></span> Tạo Mã Giảm Giá Mới
                </h2>
                <form method="POST" class="space-y-5">
                    <input type="hidden" name="action" value="add">
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <!-- Mã coupon -->
                        <div>
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">🏷️ Mã Giảm Giá</label>
                            <input type="text" name="code" required
                                   class="w-full bg-slate-50 border border-slate-200 rounded-xl p-3 text-sm font-mono uppercase focus:border-violet-500 focus:bg-white transition"
                                   placeholder="VD: SUMMER2024, WELCOME50">
                            <p class="text-xs text-slate-400 mt-1">Mã sẽ tự động chuyển thành chữ HOA</p>
                        </div>
                        
                        <!-- Loại giảm giá -->
                        <div>
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">📊 Loại Giảm Giá</label>
                            <select name="type" class="w-full bg-slate-50 border border-slate-200 rounded-xl p-3 text-sm focus:border-violet-500 focus:bg-white transition">
                                <option value="percent">🎯 Giảm theo phần trăm (%)</option>
                                <option value="fixed">💵 Giảm số tiền cố định (VNĐ)</option>
                            </select>
                        </div>
                        
                        <!-- Mức giảm -->
                        <div>
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">🔢 Mức Giảm</label>
                            <input type="number" name="discount" value="10" min="1" max="100" required
                                   class="w-full bg-slate-50 border border-slate-200 rounded-xl p-3 text-sm focus:border-violet-500 focus:bg-white transition"
                                   placeholder="Nhập % hoặc số tiền">
                            <p class="text-xs text-slate-400 mt-1">Nếu chọn %: nhập 10 = giảm 10%. Nếu chọn tiền: nhập 50000 = giảm 50.000đ</p>
                        </div>
                        
                        <!-- Số lần dùng tối đa -->
                        <div>
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">👥 Lượt Dùng Tối Đa</label>
                            <input type="number" name="max_use" value="100" min="1" required
                                   class="w-full bg-slate-50 border border-slate-200 rounded-xl p-3 text-sm focus:border-violet-500 focus:bg-white transition">
                            <p class="text-xs text-slate-400 mt-1">Số lần tối đa mã này được sử dụng</p>
                        </div>
                        
                        <!-- Đơn tối thiểu -->
                        <div>
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">💰 Đơn Hàng Tối Thiểu (VNĐ)</label>
                            <input type="number" name="min_amount" value="0" min="0" step="10000"
                                   class="w-full bg-slate-50 border border-slate-200 rounded-xl p-3 text-sm focus:border-violet-500 focus:bg-white transition">
                            <p class="text-xs text-slate-400 mt-1">0 = không giới hạn. VD: 100000 = đơn từ 100k mới áp dụng</p>
                        </div>
                        
                        <!-- Giảm tối đa -->
                        <div>
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">📉 Giảm Tối Đa (VNĐ)</label>
                            <input type="number" name="max_discount" value="0" min="0" step="10000"
                                   class="w-full bg-slate-50 border border-slate-200 rounded-xl p-3 text-sm focus:border-violet-500 focus:bg-white transition">
                            <p class="text-xs text-slate-400 mt-1">0 = không giới hạn. Áp dụng cho loại giảm theo %</p>
                        </div>
                    </div>

                    <!-- Ngày hết hạn & Mô tả -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">📅 Ngày Hết Hạn</label>
                            <input type="date" name="expire_date"
                                   class="w-full bg-slate-50 border border-slate-200 rounded-xl p-3 text-sm focus:border-violet-500 focus:bg-white transition">
                            <p class="text-xs text-slate-400 mt-1">Để trống nếu không giới hạn thời gian</p>
                        </div>
                        <div>
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">📝 Mô Tả</label>
                            <input type="text" name="description"
                                   class="w-full bg-slate-50 border border-slate-200 rounded-xl p-3 text-sm focus:border-violet-500 focus:bg-white transition"
                                   placeholder="VD: Khuyến mãi mùa hè 2024">
                        </div>
                    </div>

                    <button type="submit" 
                            class="w-full md:w-auto bg-slate-900 text-white font-bold text-sm px-8 py-4 rounded-2xl hover:bg-violet-600 transition shadow-lg">
                        <i class="fas fa-plus-circle mr-2"></i> Tạo Mã Giảm Giá
                    </button>
                </form>
            </div>

            <!-- Danh Sách Coupon -->
            <div class="white-card mb-8">
                <h2 class="text-lg font-extrabold text-slate-900 mb-6 flex items-center gap-2">
                    <span class="w-1 h-6 bg-violet-600 rounded-full"></span> Danh Sách Mã Giảm Giá 
                    <span class="bg-slate-100 text-slate-600 text-xs font-bold px-3 py-1 rounded-full"><?=$totalCoupons;?> mã</span>
                </h2>
                
                <?php if($list && $list->num_rows > 0): ?>
                <div class="table-wrap overflow-x-auto">
                    <table class="w-full text-sm">
                        <thead>
                            <tr class="border-b border-slate-200 text-left">
                                <th class="p-3 text-xs font-bold text-slate-400 uppercase tracking-wider">#ID</th>
                                <th class="p-3 text-xs font-bold text-slate-400 uppercase tracking-wider">Mã</th>
                                <th class="p-3 text-xs font-bold text-slate-400 uppercase tracking-wider">Giảm</th>
                                <th class="p-3 text-xs font-bold text-slate-400 uppercase tracking-wider">Đã Dùng</th>
                                <th class="p-3 text-xs font-bold text-slate-400 uppercase tracking-wider">Đơn Tối Thiểu</th>
                                <th class="p-3 text-xs font-bold text-slate-400 uppercase tracking-wider">Hạn</th>
                                <th class="p-3 text-xs font-bold text-slate-400 uppercase tracking-wider">Mô Tả</th>
                                <th class="p-3 text-xs font-bold text-slate-400 uppercase tracking-wider">Trạng Thái</th>
                                <th class="p-3 text-xs font-bold text-slate-400 uppercase tracking-wider">Thao Tác</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while($row = $list->fetch_assoc()): 
                                $expired = !empty($row['expire_date']) && $row['expire_date'] < date('Y-m-d');
                                $full = $row['used'] >= $row['max_use'];
                                
                                if($row['status'] == 0) {
                                    $statusClass = 'bg-slate-100 text-slate-500';
                                    $statusText = '⛔ Đã tắt';
                                } elseif($expired) {
                                    $statusClass = 'bg-amber-50 text-amber-700';
                                    $statusText = '⚠️ Hết hạn';
                                } elseif($full) {
                                    $statusClass = 'bg-rose-50 text-rose-700';
                                    $statusText = '🔒 Hết lượt';
                                } else {
                                    $statusClass = 'bg-emerald-50 text-emerald-700';
                                    $statusText = '✅ Hoạt động';
                                }
                                
                                $discountText = $row['type'] == 'percent' ? '-' . $row['discount'] . '%' : '-' . number_format($row['discount'],0,',','.') . 'đ';
                            ?>
                            <tr class="border-b border-slate-100 hover:bg-slate-50 transition">
                                <td class="p-3 font-bold">#<?=$row['id'];?></td>
                                <td class="p-3 font-mono font-bold text-violet-600"><?=htmlspecialchars($row['code']);?></td>
                                <td class="p-3 font-bold text-rose-600"><?=$discountText;?></td>
                                <td class="p-3">
                                    <span class="font-bold"><?=$row['used'];?></span>
                                    <span class="text-slate-400">/ <?=$row['max_use'];?></span>
                                    <?php if($full): ?><span class="ml-2 bg-rose-50 text-rose-600 text-[10px] font-bold px-2 py-0.5 rounded-full">FULL</span><?php endif; ?>
                                </td>
                                <td class="p-3 text-slate-600"><?=$row['min_amount'] > 0 ? number_format($row['min_amount'],0,',','.').'đ' : '—';?></td>
                                <td class="p-3 text-slate-500 text-xs">
                                    <?=$row['expire_date'] ? date('d/m/Y', strtotime($row['expire_date'])) : '<span class="text-slate-300">—</span>';?>
                                </td>
                                <td class="p-3 text-slate-500 text-xs max-w-[150px] truncate"><?=htmlspecialchars($row['description'] ?? '—');?></td>
                                <td class="p-3">
                                    <span class="text-[11px] font-bold px-2.5 py-1 rounded-full <?=$statusClass;?>"><?=$statusText;?></span>
                                </td>
                                <td class="p-3">
                                    <div class="flex gap-2">
                                        <form method="POST" class="inline" onsubmit="return confirm('Xác nhận <?=$row['status']==1?'TẮT':'BẬT';?> mã này?')">
                                            <input type="hidden" name="action" value="toggle">
                                            <input type="hidden" name="id" value="<?=$row['id'];?>">
                                            <button type="submit" class="p-2 rounded-xl <?=$row['status']==1 ? 'bg-amber-50 text-amber-600 hover:bg-amber-100' : 'bg-emerald-50 text-emerald-600 hover:bg-emerald-100';?> transition">
                                                <i class="fas fa-<?=$row['status']==1?'toggle-on':'toggle-off';?>"></i>
                                            </button>
                                        </form>
                                        <form method="POST" class="inline" onsubmit="return confirm('Xác nhận XÓA mã #<?=$row['id'];?>?')">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="id" value="<?=$row['id'];?>">
                                            <button type="submit" class="p-2 rounded-xl bg-rose-50 text-rose-600 hover:bg-rose-100 transition">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <div class="text-center py-12 text-slate-400">
                    <i class="fas fa-tags text-5xl mb-4 block opacity-30"></i>
                    <p class="font-semibold">Chưa có mã giảm giá nào được tạo</p>
                </div>
                <?php endif; ?>
            </div>

            <!-- Lịch Sử Sử Dụng -->
            <div class="white-card">
                <h2 class="text-lg font-extrabold text-slate-900 mb-6 flex items-center gap-2">
                    <span class="w-1 h-6 bg-violet-600 rounded-full"></span> Lịch Sử Sử Dụng
                    <span class="bg-violet-50 text-violet-600 text-xs font-bold px-3 py-1 rounded-full">50 gần nhất</span>
                </h2>
                
                <?php if($history && $history->num_rows > 0): ?>
                <div class="table-wrap overflow-x-auto">
                    <table class="w-full text-sm">
                        <thead>
                            <tr class="border-b border-slate-200 text-left">
                                <th class="p-3 text-xs font-bold text-slate-400 uppercase tracking-wider">#ID</th>
                                <th class="p-3 text-xs font-bold text-slate-400 uppercase tracking-wider">Người Dùng</th>
                                <th class="p-3 text-xs font-bold text-slate-400 uppercase tracking-wider">Mã</th>
                                <th class="p-3 text-xs font-bold text-slate-400 uppercase tracking-wider">Đơn Hàng</th>
                                <th class="p-3 text-xs font-bold text-slate-400 uppercase tracking-wider">Tiết Kiệm</th>
                                <th class="p-3 text-xs font-bold text-slate-400 uppercase tracking-wider">Thời Gian</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while($row = $history->fetch_assoc()): ?>
                            <tr class="border-b border-slate-100 hover:bg-slate-50 transition">
                                <td class="p-3 font-bold">#<?=$row['id'];?></td>
                                <td class="p-3 font-semibold"><?=htmlspecialchars($row['username']);?></td>
                                <td class="p-3 font-mono font-bold text-violet-600"><?=htmlspecialchars($row['code']);?></td>
                                <td class="p-3 text-slate-600"><?=number_format($row['order_amount'],0,',','.');?>đ</td>
                                <td class="p-3 font-bold text-emerald-600">-<?=number_format($row['saved_amount'],0,',','.');?>đ</td>
                                <td class="p-3 text-xs text-slate-400"><?=date('d/m/Y H:i', strtotime($row['used_at']));?></td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <div class="text-center py-12 text-slate-400">
                    <i class="fas fa-receipt text-5xl mb-4 block opacity-30"></i>
                    <p class="font-semibold">Chưa có ai sử dụng mã giảm giá</p>
                </div>
                <?php endif; ?>
            </div>

        </div>
    </div>
<?php require_once('hethong/foot.php');?>
</body>
</html>