<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('../../hethong/ketnoi.php');

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

// Xử lý xóa/toggle
if(isset($_POST['delete'])) {
    $id = (int)$_POST['id'];
    $ketnoi->query("DELETE FROM giftcode WHERE id=$id");
}
if(isset($_POST['toggle'])) {
    $id = (int)$_POST['id'];
    $ketnoi->query("UPDATE giftcode SET status = 1 - status WHERE id=$id");
}

$list = $ketnoi->query("SELECT * FROM giftcode ORDER BY id DESC");
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Danh Sách Giftcode | Admin</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
    <?php include('sidebar.php'); ?>
    <div class="content-wrapper">
        <section class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1><i class="fas fa-gift text-danger mr-2"></i>Danh Sách Giftcode</h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="/admin">Admin</a></li>
                            <li class="breadcrumb-item active">Giftcode</li>
                        </ol>
                    </div>
                </div>
            </div>
        </section>

        <section class="content">
            <div class="container-fluid">
                <div class="card">
                    <div class="card-header">
                        <a href="giftcode.php" class="btn btn-success"><i class="fas fa-plus mr-1"></i>Thêm Giftcode</a>
                    </div>
                    <div class="card-body table-responsive p-0">
                        <table class="table table-hover text-nowrap">
                            <thead>
                                <tr>
                                    <th>#ID</th>
                                    <th>Mã Giftcode</th>
                                    <th>Tiền Thưởng</th>
                                    <th>Đã Dùng / Tối Đa</th>
                                    <th>Hạn Sử Dụng</th>
                                    <th>Trạng Thái</th>
                                    <th>Ngày Tạo</th>
                                    <th>Thao Tác</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if($list && $list->num_rows > 0): ?>
                                    <?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) { $status = '<span class="badge badge-secondary">Tắt</span>'; }
                                        elseif($expired) { $status = '<span class="badge badge-warning">Hết hạn</span>'; }
                                        elseif($full) { $status = '<span class="badge badge-danger">Hết lượt</span>'; }
                                        else { $status = '<span class="badge badge-success">Hoạt động</span>'; }
                                    ?>
                                    <tr>
                                        <td>#<?=$row['id'];?></td>
                                        <td><code class="text-primary font-weight-bold"><?=htmlspecialchars($row['code']);?></code></td>
                                        <td class="text-success font-weight-bold">+<?=number_format($row['money'],0,',','.');?>đ</td>
                                        <td><b><?=$row['used'];?></b> / <?=$row['max_use'];?></td>
                                        <td><?=$row['expire_date'] ? date('d/m/Y', strtotime($row['expire_date'])) : '<span class="text-muted">Không giới hạn</span>';?></td>
                                        <td><?=$status;?></td>
                                        <td><?=date('d/m/Y H:i', strtotime($row['created_at']));?></td>
                                        <td>
                                            <form method="POST" style="display:inline">
                                                <input type="hidden" name="id" value="<?=$row['id'];?>">
                                                <button type="submit" name="toggle" class="btn btn-sm btn-info" title="Bật/Tắt"><i class="fas fa-toggle-on"></i></button>
                                                <button type="submit" name="delete" class="btn btn-sm btn-danger" onclick="return confirm('Xóa mã này?')" title="Xóa"><i class="fas fa-trash"></i></button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr><td colspan="8" class="text-center text-muted py-4">Chưa có giftcode nào!</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </section>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/js/adminlte.min.js"></script>
</body>
</html>