<?php
session_start();
if ($_SESSION['unohs'] == null) {
    header("location:index.php?msg=unauthorized");
    exit();
}

include("conn.php");
date_default_timezone_set('Asia/Kolkata'); 

// --- GENERATOR FUNCTION ---
function generateRandomSerial($length = 12) {
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[random_int(0, strlen($characters) - 1)];
    }
    return $randomString;
}

// --- HANDLE GENERATE ---
if (isset($_POST['generate_codes'])) {
    $maxserials = intval($_POST['maxserials']);
    $maxusers = intval($_POST['maxusers']);
    $price = mysqli_real_escape_string($conn, $_POST['price']);
    $remark = mysqli_real_escape_string($conn, $_POST['remark']);

    if ($maxserials > 50) {
        echo '<script>alert("⚠️ Max 50 codes at a time!");</script>';
    } else {
        $createdate = date("Y-m-d H:i:s");
        for ($i = 0; $i < $maxserials; $i++) {
            $newSerial = generateRandomSerial();
            $sql = "INSERT INTO hodike_nirvahaka (enserie, utilisateurmax, prix, nombredutilisateurs, creerunrendezvous, shonu, remark) 
                    VALUES ('$newSerial', '$maxusers', '$price', '0', '$createdate', '1', '$remark')";
            mysqli_query($conn, $sql);
        }
        $msg = "✅ $maxserials Gift Codes Generated Successfully!";
    }
}

// --- HANDLE DELETE (SINGLE) ---
if (isset($_GET['del'])) {
    $id = mysqli_real_escape_string($conn, $_GET['del']);
    mysqli_query($conn, "DELETE FROM hodike_nirvahaka WHERE enserie='$id'");
    echo "<script>window.location.href='addgiftcode.php';</script>";
}

// --- HANDLE BULK DELETE ---
if (isset($_POST['bulk_delete']) && isset($_POST['check_list'])) {
    $ids = $_POST['check_list'];
    foreach($ids as $id){
        $clean_id = mysqli_real_escape_string($conn, $id);
        mysqli_query($conn, "DELETE FROM hodike_nirvahaka WHERE enserie='$clean_id'");
    }
    echo "<script>window.location.href='addgiftcode.php';</script>";
}

// --- PAGINATION ---
$limit = 10; 
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Fetch Data
$q = mysqli_query($conn, "SELECT * FROM hodike_nirvahaka ORDER BY creerunrendezvous DESC LIMIT $limit OFFSET $offset");
$total_records = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as t FROM hodike_nirvahaka"))['t'];
$total_pages = ceil($total_records / $limit);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Gift Code Manager</title>
    
    <link rel="stylesheet" href="vendors/mdi/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="vendors/base/vendor.bundle.base.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="shortcut icon" href="images/favicon.png" />

    <style>
        /* Modern Card */
        .pro-card {
            background: #fff; border-radius: 20px; 
            box-shadow: 0 10px 30px rgba(0,0,0,0.05); border: 1px solid #f0f0f0;
            margin-bottom: 30px; overflow: hidden;
        }
        .card-head {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 20px; color: white; display: flex; align-items: center; gap: 10px;
        }
        .card-head h4 { margin: 0; font-weight: 800; font-size: 1.2rem; text-transform: uppercase; }
        .card-body-custom { padding: 30px; }

        /* Inputs */
        .cool-input {
            height: 50px; border-radius: 10px; border: 2px solid #e0e0e0;
            padding: 0 15px; font-weight: 600; width: 100%; transition: 0.3s;
        }
        .cool-input:focus { border-color: #764ba2; outline: none; box-shadow: 0 0 0 4px rgba(118, 75, 162, 0.1); }
        .input-label { font-weight: 700; color: #555; margin-bottom: 8px; display: block; font-size: 0.9rem; }

        /* Buttons */
        .btn-gen {
            background: linear-gradient(135deg, #11998e, #38ef7d); color: white;
            border: none; padding: 12px 30px; border-radius: 50px; font-weight: 800;
            width: 100%; cursor: pointer; transition: 0.3s;
            box-shadow: 0 5px 15px rgba(56, 239, 125, 0.3); text-transform: uppercase;
        }
        .btn-gen:hover { transform: translateY(-3px); box-shadow: 0 8px 20px rgba(56, 239, 125, 0.4); }

        .btn-del-all {
            background: #ff4757; color: white; border: none; padding: 8px 20px; 
            border-radius: 8px; font-weight: 700; cursor: pointer; display: none;
        }

        /* Table */
        .table-responsive { overflow-x: auto; }
        .custom-table { width: 100%; border-collapse: separate; border-spacing: 0 10px; }
        .custom-table th { color: #888; font-weight: 800; text-transform: uppercase; font-size: 0.8rem; padding: 15px; text-align: left; }
        .custom-table td { background: #fff; padding: 15px; font-weight: 600; color: #444; border-top: 1px solid #f5f5f5; border-bottom: 1px solid #f5f5f5; vertical-align: middle; }
        .custom-table tr:hover td { background: #fcfcfc; }
        .custom-table td:first-child { border-left: 1px solid #f5f5f5; border-radius: 10px 0 0 10px; }
        .custom-table td:last-child { border-right: 1px solid #f5f5f5; border-radius: 0 10px 10px 0; }

        /* Code Box */
        .code-box {
            font-family: 'Courier New', monospace; font-weight: 900; color: #764ba2;
            background: #f3e5f5; padding: 5px 10px; border-radius: 6px; letter-spacing: 1px;
            display: inline-flex; align-items: center; gap: 8px;
        }
        .copy-icon { cursor: pointer; color: #aaa; transition: 0.2s; }
        .copy-icon:hover { color: #764ba2; transform: scale(1.2); }

        /* Progress Bar */
        .progress-cont { width: 100px; height: 6px; background: #eee; border-radius: 10px; overflow: hidden; margin-top: 5px; }
        .progress-fill { height: 100%; background: #00b894; border-radius: 10px; }
        .usage-text { font-size: 0.75rem; color: #888; font-weight: 700; }

        /* Status Badge */
        .badge-status { padding: 5px 10px; border-radius: 20px; font-size: 0.7rem; font-weight: 800; text-transform: uppercase; }
        .st-active { background: #e0f2f1; color: #00695c; }
        .st-full { background: #ffebee; color: #c62828; }

        /* Pagination */
        .pagination { margin-top: 20px; display: flex; justify-content: center; gap: 5px; }
        .page-link { padding: 8px 15px; background: #fff; border: 1px solid #ddd; color: #333; text-decoration: none; border-radius: 5px; font-weight: 700; }
        .page-link.active { background: #764ba2; color: white; border-color: #764ba2; }
    </style>
</head>

<body>
<div class="container-scroller">
    <nav class="navbar col-lg-12 col-12 p-0 fixed-top d-flex flex-row">
        <div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-center">
            <a class="navbar-brand brand-logo" href="dashboard.php"><h4 style="color:#764ba2; font-weight:900;">ADMIN PANEL</h4></a>
        </div>
        <div class="navbar-menu-wrapper d-flex align-items-center justify-content-end">
            <ul class="navbar-nav navbar-nav-right">
                <li class="nav-item"><a class="nav-link" href="logout.php"><i class="fa-solid fa-power-off" style="color:red;"></i> Logout</a></li>
            </ul>
        </div>
    </nav>

    <div class="container-fluid page-body-wrapper">
        <nav class="sidebar sidebar-offcanvas" id="sidebar">
            <div class="user-profile">
                <div class="user-image"><img src="images/faces/face28.png"></div>
                <div class="user-name">AB Coders</div>
                <div class="user-designation">Admin</div>
            </div>
            <?php include 'compass.php'; ?>
        </nav>

        <div class="main-panel">
            <div class="content-wrapper">
                
                <?php if(isset($msg)) echo "<div class='alert alert-success'>$msg</div>"; ?>

                <div class="row">
                    <div class="col-md-12 col-lg-4">
                        <div class="pro-card">
                            <div class="card-head">
                                <i class="fa-solid fa-wand-magic-sparkles"></i>
                                <h4>Create Codes</h4>
                            </div>
                            <div class="card-body-custom">
                                <form method="post">
                                    <div class="form-group mb-3">
                                        <label class="input-label">Quantity (How many codes?)</label>
                                        <input type="number" name="maxserials" class="cool-input" placeholder="Ex: 10" min="1" max="50" required>
                                    </div>
                                    <div class="form-group mb-3">
                                        <label class="input-label">Max Users (Per Code)</label>
                                        <input type="number" name="maxusers" class="cool-input" placeholder="Ex: 100" required>
                                    </div>
                                    <div class="form-group mb-3">
                                        <label class="input-label">Amount (Price)</label>
                                        <input type="number" name="price" class="cool-input" placeholder="₹ Amount" required>
                                    </div>
                                    <div class="form-group mb-4">
                                        <label class="input-label">Remark</label>
                                        <input type="text" name="remark" class="cool-input" placeholder="Ex: Diwali Bonus" required>
                                    </div>
                                    <button type="submit" name="generate_codes" class="btn-gen">GENERATE NOW</button>
                                </form>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-12 col-lg-8">
                        <div class="pro-card">
                            <div class="card-head" style="background:#fff; border-bottom:1px solid #eee; color:#333; justify-content:space-between;">
                                <div style="display:flex; align-items:center; gap:10px;">
                                    <i class="fa-solid fa-list-check" style="color:#764ba2; font-size:1.2rem;"></i>
                                    <h4 style="color:#333;">Code History</h4>
                                </div>
                                <form method="post" id="bulkForm" onsubmit="return confirm('Delete selected codes?');">
                                    <button type="submit" name="bulk_delete" id="bulkBtn" class="btn-del-all"><i class="fa-solid fa-trash"></i> DELETE SELECTED</button>
                                </form>
                            </div>
                            
                            <div class="table-responsive" style="padding:0 20px 20px 20px;">
                                <table class="custom-table">
                                    <thead>
                                        <tr>
                                            <th style="width:30px;"><input type="checkbox" id="selectAll"></th>
                                            <th>Gift Code</th>
                                            <th>Amount</th>
                                            <th>Usage</th>
                                            <th>Date</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php while($row = mysqli_fetch_assoc($q)){ 
                                            $percent = ($row['utilisateurmax'] > 0) ? ($row['nombredutilisateurs'] / $row['utilisateurmax']) * 100 : 0;
                                            $status = ($percent >= 100) ? '<span class="badge-status st-full">FULL</span>' : '<span class="badge-status st-active">ACTIVE</span>';
                                        ?>
                                        <tr>
                                            <td><input type="checkbox" name="check_list[]" value="<?php echo $row['enserie']; ?>" form="bulkForm" class="chk-item"></td>
                                            <td>
                                                <div class="code-box">
                                                    <?php echo $row['enserie']; ?>
                                                    <i class="fa-regular fa-copy copy-icon" onclick="copyText('<?php echo $row['enserie']; ?>')"></i>
                                                </div>
                                                <div style="font-size:0.75rem; color:#999; margin-top:3px;"><?php echo $row['remark']; ?></div>
                                            </td>
                                            <td style="color:#00b894; font-weight:800; font-size:1.1rem;">₹<?php echo $row['prix']; ?></td>
                                            <td>
                                                <div class="usage-text"><?php echo $row['nombredutilisateurs']; ?> / <?php echo $row['utilisateurmax']; ?> Users</div>
                                                <div class="progress-cont"><div class="progress-fill" style="width:<?php echo $percent; ?>%;"></div></div>
                                                <?php echo $status; ?>
                                            </td>
                                            <td style="font-size:0.85rem;">
                                                <i class="fa-regular fa-calendar"></i> <?php echo date("d M Y", strtotime($row['creerunrendezvous'])); ?><br>
                                                <span style="color:#aaa;"><?php echo date("h:i A", strtotime($row['creerunrendezvous'])); ?></span>
                                            </td>
                                            <td>
                                                <a href="addgiftcode.php?del=<?php echo $row['enserie']; ?>" onclick="return confirm('Delete this code?')" style="color:#ff4757; font-size:1.2rem;">
                                                    <i class="fa-solid fa-trash-can"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>

                                <div class="pagination">
                                    <?php for($i=1; $i<=$total_pages; $i++){ ?>
                                        <a href="?page=<?php echo $i; ?>" class="page-link <?php if($i==$page) echo 'active'; ?>"><?php echo $i; ?></a>
                                    <?php } ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
            <footer class="footer"><div class="d-sm-flex justify-content-center"><span class="text-muted">Copyright © 2026 AB Coders</span></div></footer>
        </div>
    </div>
</div>

<script src="vendors/base/vendor.bundle.base.js"></script>
<script src="js/off-canvas.js"></script>
<script src="js/hoverable-collapse.js"></script>
<script src="js/template.js"></script>

<script>
    // Copy Function
    function copyText(text) {
        navigator.clipboard.writeText(text).then(function() {
            alert('Code Copied: ' + text);
        });
    }

    // Select All Logic
    document.getElementById('selectAll').addEventListener('change', function() {
        let checkboxes = document.querySelectorAll('.chk-item');
        checkboxes.forEach(cb => cb.checked = this.checked);
        toggleDelBtn();
    });

    // Show/Hide Delete Button
    document.querySelectorAll('.chk-item').forEach(cb => {
        cb.addEventListener('change', toggleDelBtn);
    });

    function toggleDelBtn() {
        let checked = document.querySelectorAll('.chk-item:checked').length;
        document.getElementById('bulkBtn').style.display = checked > 0 ? 'inline-block' : 'none';
    }
</script>

</body>
</html>