<?php
// Enable Error Reporting
ini_set('display_errors', 1);
error_reporting(E_ALL);

require 'auth_check.php';
require '../config/db.php';

$msg = "";
$msgClass = "";

try {
    // 1. ADD BULK KEYS
    if (isset($_POST['add_keys'])) {
        $product_id = $_POST['product_id'];
        // Normalize new lines
        $raw_keys = str_replace(["\r\n", "\r"], "\n", $_POST['key_list']);
        $keys_array = explode("\n", $raw_keys);
        
        $count = 0;
        $stmt = $pdo->prepare("INSERT INTO license_keys (product_id, license_key, status) VALUES (?, ?, 'available')");

        foreach ($keys_array as $key) {
            $key = trim($key);
            if (!empty($key)) {
                $stmt->execute([$product_id, $key]);
                $count++;
            }
        }
        $msg = "Success! $count keys added to inventory.";
        $msgClass = "success";
    }

    // 2. UPDATE SINGLE KEY (Edit Feature)
    if (isset($_POST['update_key'])) {
        $key_id = $_POST['key_id'];
        $key_val = trim($_POST['license_key']);
        $status = $_POST['status'];
        $return_pid = $_POST['return_pid']; // To stay on the same view

        $pdo->prepare("UPDATE license_keys SET license_key = ?, status = ? WHERE id = ?")
            ->execute([$key_val, $status, $key_id]);
        
        header("Location: keys.php?view_product=$return_pid&msg=updated");
        exit();
    }

    // 3. DELETE KEY
    if (isset($_GET['delete'])) {
        $id = $_GET['delete'];
        // Get product ID first to return to view
        $chk = $pdo->prepare("SELECT product_id FROM license_keys WHERE id=?");
        $chk->execute([$id]);
        $pid = $chk->fetchColumn();

        $pdo->prepare("DELETE FROM license_keys WHERE id = ?")->execute([$id]);
        
        header("Location: keys.php?view_product=$pid&msg=deleted");
        exit();
    }

    // 4. FETCH STATS (Grouped by Product)
    $stats = $pdo->query("
        SELECT p.id as pid, p.name, 
        COUNT(CASE WHEN k.status = 'available' THEN 1 END) as available_count,
        COUNT(CASE WHEN k.status = 'used' THEN 1 END) as used_count
        FROM products p
        LEFT JOIN license_keys k ON p.id = k.product_id
        GROUP BY p.id
        HAVING available_count > 0 OR used_count > 0
    ")->fetchAll();

    // 5. FETCH ALL PRODUCTS (For Dropdown)
    $products = $pdo->query("SELECT id, name FROM products WHERE is_active=1")->fetchAll();

    // 6. FETCH KEYS FOR SPECIFIC PRODUCT (If View Clicked)
    $view_keys = [];
    $view_product_name = "";
    if (isset($_GET['view_product'])) {
        $vpid = $_GET['view_product'];
        
        // Get Product Name
        $pnStmt = $pdo->prepare("SELECT name FROM products WHERE id = ?");
        $pnStmt->execute([$vpid]);
        $view_product_name = $pnStmt->fetchColumn();

        // Get Keys
        $vkStmt = $pdo->prepare("SELECT * FROM license_keys WHERE product_id = ? ORDER BY status ASC, id DESC");
        $vkStmt->execute([$vpid]);
        $view_keys = $vkStmt->fetchAll();
    }

} catch (Exception $e) {
    die("Database Error: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Manage Keys</title>
    <link rel="stylesheet" href="admin_style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .msg-box { padding: 10px; border-radius: 5px; margin-bottom: 20px; text-align: center; }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        
        .grid-container { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        @media(max-width: 800px) { .grid-container { grid-template-columns: 1fr; } }

        .stat-row { display: flex; justify-content: space-between; padding: 10px; border-bottom: 1px solid #eee; align-items: center; }
        .stat-row:last-child { border-bottom: none; }
        
        /* Edit Table */
        .edit-table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        .edit-table th { background: #f1f1f1; padding: 8px; text-align: left; font-size: 12px; }
        .edit-table td { padding: 8px; border-bottom: 1px solid #eee; }
        .input-key { width: 100%; padding: 5px; border: 1px solid #ddd; font-family: monospace; }
        .status-select { padding: 5px; border: 1px solid #ddd; }
        
        .btn-sm { padding: 4px 8px; font-size: 12px; border-radius: 3px; text-decoration: none; color: white; cursor: pointer; border: none; }
        .btn-save { background: #27ae60; }
        .btn-del { background: #c0392b; }
    </style>
</head>
<body>


            <div class="sidebar">
        <?php include 'sidebar.php'; ?>
    </div>

    <div class="content">
        <h1 style="margin-bottom: 20px;">Automated Key Manager</h1>
        
        <?php if($msg || isset($_GET['msg'])): ?>
            <div class="msg-box success">
                <?php echo $msg ? $msg : "Action completed successfully."; ?>
            </div>
        <?php endif; ?>

        <div class="grid-container">
            
            <div style="background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); height: fit-content;">
                <h3 style="margin-top:0; border-bottom: 2px solid #3498db; padding-bottom: 10px; color: #3498db;">
                    <i class="fas fa-plus-circle"></i> Add Keys
                </h3>
                <form method="POST">
                    <label style="font-weight: bold; display:block; margin-bottom:5px;">Select Product</label>
                    <select name="product_id" required style="width: 100%; padding: 10px; border: 1px solid #ddd; margin-bottom: 15px;">
                        <?php foreach($products as $p): ?>
                            <option value="<?php echo $p['id']; ?>"><?php echo htmlspecialchars($p['name']); ?></option>
                        <?php endforeach; ?>
                    </select>

                    <label style="font-weight: bold; display:block; margin-bottom:5px;">Paste Keys (One per line)</label>
                    <textarea name="key_list" rows="8" placeholder="XXXX-YYYY-ZZZZ&#10;user:pass&#10;http://activation-link.com" required style="width: 100%; padding: 10px; border: 1px solid #ddd; box-sizing: border-box;"></textarea>

                    <button type="submit" name="add_keys" class="btn btn-primary" style="width:100%; margin-top: 10px;">Import to Pool</button>
                </form>
            </div>

            <div style="background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05);">
                <h3 style="margin-top:0; border-bottom: 2px solid #f39c12; padding-bottom: 10px; color: #f39c12;">
                    <i class="fas fa-boxes"></i> Inventory Status
                </h3>
                <?php if(empty($stats)): ?>
                    <p style="color:#777; text-align:center; margin-top:20px;">No keys added yet.</p>
                <?php else: ?>
                    <?php foreach($stats as $s): ?>
                        <div class="stat-row">
                            <div>
                                <strong><?php echo htmlspecialchars($s['name']); ?></strong><br>
                                <span style="font-size: 12px; color: #777;">Total: <?php echo $s['available_count'] + $s['used_count']; ?></span>
                            </div>
                            <div style="text-align: right;">
                                <span style="color: green; font-weight: bold;"><?php echo $s['available_count']; ?> Available</span><br>
                                <a href="keys.php?view_product=<?php echo $s['pid']; ?>" style="font-size: 12px; color: blue; text-decoration: none;">View / Edit</a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

        </div>

        <?php if(!empty($view_keys)): ?>
        <div style="margin-top: 30px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05);">
            <h3 style="margin-top:0; color: #2c3e50;">
                Editing Keys for: <span style="color: #3498db;"><?php echo htmlspecialchars($view_product_name); ?></span>
                <a href="keys.php" style="float: right; font-size: 14px; color: #e74c3c; text-decoration: none;">&times; Close</a>
            </h3>
            
            <table class="edit-table">
                <thead>
                    <tr>
                        <th width="5%">ID</th>
                        <th width="60%">License Key / Data</th>
                        <th width="15%">Status</th>
                        <th width="10%">Assigned Order</th>
                        <th width="10%">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($view_keys as $k): ?>
                    <tr>
                        <form method="POST">
                            <input type="hidden" name="key_id" value="<?php echo $k['id']; ?>">
                            <input type="hidden" name="return_pid" value="<?php echo $vpid; ?>">
                            
                            <td><?php echo $k['id']; ?></td>
                            <td>
                                <input type="text" name="license_key" class="input-key" value="<?php echo htmlspecialchars($k['license_key']); ?>">
                            </td>
                            <td>
                                <select name="status" class="status-select" style="color: <?php echo $k['status']=='available'?'green':'red'; ?>;">
                                    <option value="available" <?php echo $k['status']=='available'?'selected':''; ?>>Available</option>
                                    <option value="used" <?php echo $k['status']=='used'?'selected':''; ?>>Used</option>
                                </select>
                            </td>
                            <td style="text-align: center; color: #777;">
                                <?php echo $k['order_id'] ? "#".$k['order_id'] : '-'; ?>
                            </td>
                            <td>
                                <button type="submit" name="update_key" class="btn-sm btn-save"><i class="fas fa-save"></i></button>
                                <a href="keys.php?delete=<?php echo $k['id']; ?>" class="btn-sm btn-del" onclick="return confirm('Delete this key?')"><i class="fas fa-trash"></i></a>
                            </td>
                        </form>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>

    </div>
</body>
</html>