<?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 giftcode
$sql1 = "CREATE TABLE IF NOT EXISTS `giftcode` (
  `id` int NOT NULL AUTO_INCREMENT,
  `code` varchar(50) NOT NULL,
  `money` 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,
  `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ử
$sql2 = "CREATE TABLE IF NOT EXISTS `giftcode_history` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(100) NOT NULL,
  `code` varchar(50) NOT NULL,
  `money` 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 GIFTCODE
    if($action === 'add') {
        $codes    = isset($_POST['codes']) ? trim($_POST['codes']) : '';
        $money    = isset($_POST['money']) ? (int)$_POST['money'] : 0;
        $max_use  = isset($_POST['max_use']) ? (int)$_POST['max_use'] : 1;
        $expire   = isset($_POST['expire_date']) ? trim($_POST['expire_date']) : '';

        if(empty($codes) || $money <= 0) {
            $message = 'Vui lòng nhập đầy đủ mã và số tiền!';
            $msgType = 'error';
        } else {
            $codeList = preg_split('/[\r\n,;]+/', $codes);
            $codeList = array_map('trim', $codeList);
            $codeList = array_map('strtoupper', $codeList);
            $codeList = array_filter($codeList);
            $codeList = array_unique($codeList);

            $success = 0;
            $fail = 0;
            $errors = [];

            $expireVal = !empty($expire) ? "'" . $ketnoi->real_escape_string($expire) . "'" : "NULL";

            foreach($codeList as $code) {
                $code = $ketnoi->real_escape_string($code);
                
                $check = $ketnoi->query("SELECT id FROM `giftcode` WHERE `code`='$code'");
                if($check && $check->num_rows > 0) {
                    $fail++;
                    $errors[] = "$code (đã tồn tại)";
                    continue;
                }

                $insert = $ketnoi->query("INSERT INTO `giftcode` (`code`,`money`,`max_use`,`expire_date`,`status`,`created_at`) VALUES ('$code',$money,$max_use,$expireVal,1,NOW())");
                if($insert) {
                    $success++;
                } else {
                    $fail++;
                    $errors[] = "$code (lỗi: " . $ketnoi->error . ")";
                }
            }

            if($success > 0) {
                $message = "✅ Đã thêm thành công <b>$success</b> giftcode!";
                if($fail > 0) $message .= "<br>❌ <b>$fail</b> mã bị lỗi: " . implode(', ', $errors);
                $msgType = 'success';
            } else {
                $message = "❌ Không thể thêm giftcode! " . implode(', ', $errors);
                $msgType = 'error';
            }
        }
    }

    // XÓA GIFTCODE
    if($action === 'delete') {
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        if($id > 0) {
            $ketnoi->query("DELETE FROM `giftcode` WHERE `id`=$id");
            $message = '✅ Đã xóa giftcode!';
            $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 `giftcode` 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 giftcode
$list = $ketnoi->query("SELECT * FROM `giftcode` ORDER BY `id` DESC");
$totalCodes = ($list) ? $list->num_rows : 0;

// Thống kê
$statsQuery = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status=1 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,
    SUM(money * used) as total_money_given
FROM `giftcode`";
$statsResult = $ketnoi->query($statsQuery);
$stats = ($statsResult) ? $statsResult->fetch_assoc() : [
    'total' => 0, 'active' => 0, 'inactive' => 0, 'expired' => 0,
    'total_used' => 0, 'total_max' => 0, 'total_money_given' => 0
];

// Lịch sử sử dụng
$history = $ketnoi->query("SELECT * FROM `giftcode_history` ORDER BY `id` DESC LIMIT 50");
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <?php require_once('hethong/head2.php');?>
    <title>Quản Lý Giftcode | 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(200px, 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: 2rem; 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-indigo-100 text-indigo-600 rounded-xl flex items-center justify-center">
                            <i class="fas fa-gifts text-lg"></i>
                        </span>
                        Quản Lý Giftcode
                    </h1>
                    <p class="text-slate-500 mt-1">Tạo & quản lý mã quà tặng cho người dùng</p>
                </div>
                <a href="#formSection" class="bg-indigo-600 text-white font-bold text-sm px-6 py-3 rounded-2xl hover:bg-indigo-700 transition shadow-lg shadow-indigo-200">
                    <i class="fas fa-plus mr-2"></i> Tạo Giftcode 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-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 class="white-card">
                    <p class="text-amber-600 text-xs font-bold uppercase tracking-wider">💰 Tiền Đã Phát</p>
                    <div class="stat-val text-amber-600 text-2xl"><?=number_format($stats['total_money_given']);?><span class="text-lg text-slate-400 font-medium ml-1">đ</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 Giftcode -->
            <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-indigo-600 rounded-full"></span> Tạo Giftcode Mới
                </h2>
                <form method="POST" class="space-y-5">
                    <input type="hidden" name="action" value="add">
                    
                    <div>
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">📝 Danh Sách Mã Giftcode</label>
                        <textarea name="codes" rows="4" required
                                  class="w-full bg-slate-50 border border-slate-200 rounded-xl p-4 text-sm font-mono focus:border-indigo-500 focus:bg-white transition resize-none"
                                  placeholder="Nhập mã giftcode, mỗi mã 1 dòng hoặc cách nhau bằng dấu phẩy (,)&#10;VD:&#10;KHANHCODER2024&#10;WELCOME50&#10;SUMMER2024,SUMMER2024VIP"></textarea>
                        <p class="text-xs text-slate-400 mt-1">💡 Mỗi dòng 1 mã, hoặc cách nhau bằng dấu phẩy. Mã sẽ tự động chuyển thành chữ HOA.</p>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div>
                            <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">💰 Số Tiền Thưởng</label>
                            <input type="number" name="money" value="50000" min="1000" step="1000" required
                                   class="w-full bg-slate-50 border border-slate-200 rounded-xl p-3 text-sm focus:border-indigo-500 focus:bg-white transition">
                            <p class="text-xs text-slate-400 mt-1">Tiền cộng vào ví (VNĐ)</p>
                        </div>
                        <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="1" min="1" required
                                   class="w-full bg-slate-50 border border-slate-200 rounded-xl p-3 text-sm focus:border-indigo-500 focus:bg-white transition">
                            <p class="text-xs text-slate-400 mt-1">1 = 1 người, 100 = 100 người</p>
                        </div>
                        <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-indigo-500 focus:bg-white transition">
                            <p class="text-xs text-slate-400 mt-1">Để trống nếu không giới hạn</p>
                        </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-indigo-600 transition shadow-lg">
                        <i class="fas fa-plus-circle mr-2"></i> Tạo Giftcode Ngay
                    </button>
                </form>
            </div>

            <!-- Danh Sách Giftcode -->
            <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-indigo-600 rounded-full"></span> Danh Sách Giftcode 
                    <span class="bg-slate-100 text-slate-600 text-xs font-bold px-3 py-1 rounded-full"><?=$totalCodes;?> 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">Tiền</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">Hạn</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">Ngày Tạo</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 = '🔒 Đã dùng hết';
                                } else {
                                    $statusClass = 'bg-emerald-50 text-emerald-700';
                                    $statusText = '✅ Hoạt động';
                                }
                            ?>
                            <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-indigo-600"><?=htmlspecialchars($row['code']);?></td>
                                <td class="p-3 font-bold text-emerald-600">+<?=number_format($row['money'],0,',','.');?>đ</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-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">
                                    <span class="text-[11px] font-bold px-2.5 py-1 rounded-full <?=$statusClass;?>"><?=$statusText;?></span>
                                </td>
                                <td class="p-3 text-xs text-slate-400"><?=date('d/m/Y H:i', strtotime($row['created_at']));?></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-ticket-simple text-5xl mb-4 block opacity-30"></i>
                    <p class="font-semibold">Chưa có giftcode nào được tạo</p>
                </div>
                <?php endif; ?>
            </div>

            <!-- Lịch Sử -->
            <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-indigo-600 rounded-full"></span> Lịch Sử Sử Dụng
                    <span class="bg-indigo-50 text-indigo-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">Tiền</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-indigo-600"><?=htmlspecialchars($row['code']);?></td>
                                <td class="p-3 font-bold text-emerald-600">+<?=number_format($row['money'],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-clock-rotate-left text-5xl mb-4 block opacity-30"></i>
                    <p class="font-semibold">Chưa có ai sử dụng giftcode</p>
                </div>
                <?php endif; ?>
            </div>

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