<?php
require_once '../includes/config.php';
require_once '../includes/telegram.php';
require_once '../includes/commission.php';
requireAdmin();
$db = getDB();

// Auto-create tables
try {
    $db->exec("CREATE TABLE IF NOT EXISTS card_categories (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, icon VARCHAR(20) DEFAULT '🎴', color VARCHAR(20) DEFAULT '#1a3c8f', description TEXT, image VARCHAR(255) DEFAULT NULL, sort_order INT DEFAULT 0, is_active TINYINT(1) DEFAULT 1, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
    $db->exec("CREATE TABLE IF NOT EXISTS cards (id INT AUTO_INCREMENT PRIMARY KEY, category_id INT NOT NULL, name VARCHAR(200) NOT NULL, description TEXT, image VARCHAR(255) DEFAULT NULL, price DECIMAL(10,2) NOT NULL DEFAULT 0, original_price DECIMAL(10,2) DEFAULT NULL, commission DECIMAL(10,2) DEFAULT 0, validity VARCHAR(100) DEFAULT NULL, region VARCHAR(100) DEFAULT NULL, stock INT DEFAULT 0, is_active TINYINT(1) DEFAULT 1, sort_order INT DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
    try { $db->exec("ALTER TABLE cards ADD COLUMN commission DECIMAL(10,2) DEFAULT 0 AFTER original_price"); } catch(Exception $e) {}
    $db->exec("CREATE TABLE IF NOT EXISTS card_pins (id INT AUTO_INCREMENT PRIMARY KEY, card_id INT NOT NULL, pin_code VARCHAR(500) NOT NULL, serial_number VARCHAR(200) DEFAULT NULL, extra_info TEXT DEFAULT NULL, status ENUM('available','sold','reserved') DEFAULT 'available', sold_to INT DEFAULT NULL, sold_at TIMESTAMP NULL, order_id INT DEFAULT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
    $db->exec("CREATE TABLE IF NOT EXISTS card_orders (id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, card_id INT NOT NULL, pin_id INT DEFAULT NULL, quantity INT DEFAULT 1, unit_price DECIMAL(10,2) NOT NULL, total_price DECIMAL(10,2) NOT NULL, commission_amount DECIMAL(10,2) DEFAULT 0, balance_before DECIMAL(10,2), balance_after DECIMAL(10,2), reference VARCHAR(50), status ENUM('pending','completed','failed','refunded') DEFAULT 'pending', note TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
} catch(Exception $e) {}

// Default categories
$cnt = $db->query("SELECT COUNT(*) FROM card_categories")->fetchColumn();
if (!$cnt) {
    $cats = [['Netflix','🎬','#E50914'],['Gaming','🎮','#7B2FBE'],['Google Play','▶️','#01875F'],['iTunes/Apple','🍎','#555555'],['Gift Cards','🎁','#F7941D'],['Steam','🎯','#1B2838']];
    $ins = $db->prepare("INSERT INTO card_categories (name,icon,color) VALUES (?,?,?)");
    foreach($cats as $c) $ins->execute($c);
}

$msg = null;
if (isset($_GET['ok'])) $msg = ['ok'=>true,'text'=>'✅ Saved successfully!'];

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

    // ===== CATEGORY ACTIONS =====
    if ($action === 'cat_save') {
        $catId = intval($_POST['cat_id'] ?? 0);
        $name  = sanitize($_POST['cat_name'] ?? '');
        $icon  = sanitize($_POST['cat_icon'] ?? '🎴');
        $color = sanitize($_POST['cat_color'] ?? '#1a3c8f');
        $desc  = sanitize($_POST['cat_desc'] ?? '');
        $sort  = intval($_POST['cat_sort'] ?? 0);

        // Handle image upload
        $catImg = $_POST['cat_existing_img'] ?? null;
        if (!empty($_FILES['cat_image']['name'])) {
            $ext = strtolower(pathinfo($_FILES['cat_image']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg','jpeg','png','webp','gif'])) {
                $dir = '../assets/img/cards/categories/';
                if (!is_dir($dir)) mkdir($dir, 0755, true);
                $fn = 'cat_'.time().'.'.$ext;
                if (move_uploaded_file($_FILES['cat_image']['tmp_name'], $dir.$fn))
                    $catImg = 'assets/img/cards/categories/'.$fn;
            }
        }

        if ($catId) {
            $db->prepare("UPDATE card_categories SET name=?,icon=?,color=?,description=?,image=?,sort_order=? WHERE id=?")->execute([$name,$icon,$color,$desc,$catImg,$sort,$catId]);
            $msg = ['ok'=>true,'text'=>'Category updated!'];
            header('Location: cards.php?ok=1'); exit;
        } else {
            $db->prepare("INSERT INTO card_categories (name,icon,color,description,image,sort_order) VALUES (?,?,?,?,?,?)")->execute([$name,$icon,$color,$desc,$catImg,$sort]);
            $msg = ['ok'=>true,'text'=>'Category added!'];
            header('Location: cards.php?ok=1'); exit;
        }
    }

    if ($action === 'cat_toggle') {
        $db->prepare("UPDATE card_categories SET is_active=1-is_active WHERE id=?")->execute([intval($_POST['cat_id'])]);
        $msg = ['ok'=>true,'text'=>'Status changed!'];
        header('Location: cards.php?ok=1'); exit;
    }
    if ($action === 'cat_delete') {
        $db->prepare("DELETE FROM card_categories WHERE id=?")->execute([intval($_POST['cat_id'])]);
        $msg = ['ok'=>true,'text'=>'Deleted!'];
        header('Location: cards.php?ok=1'); exit;
    }

    // ===== CARD ACTIONS =====
    if ($action === 'card_save') {
        $cardId   = intval($_POST['card_id'] ?? 0);
        $catId    = intval($_POST['card_cat'] ?? 0);
        $name     = sanitize($_POST['card_name'] ?? '');
        $desc     = sanitize($_POST['card_desc'] ?? '');
        $price    = floatval($_POST['card_price'] ?? 0);
        $origPrice= floatval($_POST['card_orig_price'] ?? 0) ?: null;
        $validity = sanitize($_POST['card_validity'] ?? '');
        $region   = sanitize($_POST['card_region'] ?? '');
        $sort     = intval($_POST['card_sort'] ?? 0);

        $cardImg = $_POST['card_existing_img'] ?? null;
        if (!empty($_FILES['card_image']['name'])) {
            $ext = strtolower(pathinfo($_FILES['card_image']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg','jpeg','png','webp','gif'])) {
                $dir = '../assets/img/cards/';
                if (!is_dir($dir)) mkdir($dir, 0755, true);
                $fn = 'card_'.time().'.'.$ext;
                if (move_uploaded_file($_FILES['card_image']['tmp_name'], $dir.$fn))
                    $cardImg = 'assets/img/cards/'.$fn;
            }
        }

        if ($cardId) {
            $commission = floatval($_POST["card_commission"] ?? 0);
            $db->prepare("UPDATE cards SET category_id=?,name=?,description=?,image=?,price=?,original_price=?,commission=?,validity=?,region=?,sort_order=? WHERE id=?")->execute([$catId,$name,$desc,$cardImg,$price,$origPrice,$commission,$validity,$region,$sort,$cardId]);
            $msg = ['ok'=>true,'text'=>'Card updated!'];
            header('Location: cards.php?ok=1'); exit;
        } else {
            $commission = floatval($_POST["card_commission"] ?? 0);
            $db->prepare("INSERT INTO cards (category_id,name,description,image,price,original_price,commission,validity,region,sort_order) VALUES (?,?,?,?,?,?,?,?,?,?)")->execute([$catId,$name,$desc,$cardImg,$price,$origPrice,$commission,$validity,$region,$sort]);
            $msg = ['ok'=>true,'text'=>'Card added!'];
            header('Location: cards.php?ok=1'); exit;
        }
        // Update stock count
        $cid = $cardId ?: $db->lastInsertId();
        $stock = $db->prepare("SELECT COUNT(*) FROM card_pins WHERE card_id=? AND status='available'");
        $stock->execute([$cid]);
        $db->prepare("UPDATE cards SET stock=? WHERE id=?")->execute([$stock->fetchColumn(), $cid]);
    }

    if ($action === 'card_toggle') {
        $db->prepare("UPDATE cards SET is_active=1-is_active WHERE id=?")->execute([intval($_POST['card_id'])]);
        $msg = ['ok'=>true,'text'=>'Status changed!'];
        header('Location: cards.php?ok=1'); exit;
    }
    if ($action === 'card_delete') {
        $db->prepare("DELETE FROM card_pins WHERE card_id=?")->execute([intval($_POST['card_id'])]);
        $db->prepare("DELETE FROM cards WHERE id=?")->execute([intval($_POST['card_id'])]);
        $msg = ['ok'=>true,'text'=>'Deleted!'];
        header('Location: cards.php?ok=1'); exit;
    }

    // ===== PIN ACTIONS =====
    if ($action === 'pin_add') {
        $cardId = intval($_POST['pin_card_id'] ?? 0);
        $added  = 0;

        // Handle Excel/CSV file upload
        if (!empty($_FILES['pin_excel']['name'])) {
            $ext = strtolower(pathinfo($_FILES['pin_excel']['name'], PATHINFO_EXTENSION));
            $tmpFile = $_FILES['pin_excel']['tmp_name'];

            if ($ext === 'csv') {
                // Parse CSV
                $handle = fopen($tmpFile, 'r');
                $firstRow = true;
                while (($row = fgetcsv($handle)) !== false) {
                    if ($firstRow) {
                        // Skip header if first col contains 'pin' text
                        if (stripos($row[0]??'', 'pin') !== false) { $firstRow=false; continue; }
                        $firstRow = false;
                    }
                    $pin    = trim($row[0] ?? '');
                    $serial = trim($row[1] ?? '');
                    $extra  = trim($row[2] ?? '');
                    if ($pin) {
                        $db->prepare("INSERT IGNORE INTO card_pins (card_id,pin_code,serial_number,extra_info) VALUES (?,?,?,?)")->execute([$cardId,$pin,$serial,$extra]);
                        $added++;
                    }
                }
                fclose($handle);
            } else {
                $msg = ['ok'=>false,'text'=>'Please upload CSV file. Convert Excel to CSV first.'];
            }
        }

        // Manual text input (existing system)
        if (isset($_POST['pin_codes']) && trim($_POST['pin_codes'])) {
            $pins   = array_filter(array_map('trim', explode("\n", $_POST['pin_codes'])));
            $serial = sanitize($_POST['pin_serial'] ?? '');
            $extra  = sanitize($_POST['pin_extra'] ?? '');
            foreach ($pins as $pin) {
                if ($pin) {
                    // Support pipe-separated: PIN|SERIAL|EXTRA
                    $parts = explode('|', $pin);
                    $db->prepare("INSERT IGNORE INTO card_pins (card_id,pin_code,serial_number,extra_info) VALUES (?,?,?,?)")
                       ->execute([$cardId, trim($parts[0]), trim($parts[1]??$serial), trim($parts[2]??$extra)]);
                    $added++;
                }
            }
        }

        if (!isset($msg)) {
            // Update stock
            $stock = $db->prepare("SELECT COUNT(*) FROM card_pins WHERE card_id=? AND status='available'");
            $stock->execute([$cardId]);
            $db->prepare("UPDATE cards SET stock=? WHERE id=?")->execute([$stock->fetchColumn(), $cardId]);
            $msg = ['ok'=>true,'text'=>$added.' PIN(s) added!'];
            header('Location: cards.php?ok=1'); exit;
        }
    }

    if ($action === 'pin_delete') {
        $pinId  = intval($_POST['pin_id']);
        $cardId = intval($_POST['pin_card_id']);
        $db->prepare("DELETE FROM card_pins WHERE id=? AND status='available'")->execute([$pinId]);
        $stock = $db->prepare("SELECT COUNT(*) FROM card_pins WHERE card_id=? AND status='available'");
        $stock->execute([$cardId]);
        $db->prepare("UPDATE cards SET stock=? WHERE id=?")->execute([$stock->fetchColumn(), $cardId]);
        $msg = ['ok'=>true,'text'=>'PIN deleted!'];
        header('Location: cards.php?ok=1'); exit;
    }

    // ===== ORDER ACTIONS =====
    if ($action === 'order_refund') {
        $orderId = intval($_POST['order_id']);
        $order = $db->prepare("SELECT o.*, u.balance FROM card_orders o JOIN users u ON o.user_id=u.id WHERE o.id=?");
        $order->execute([$orderId]); $o = $order->fetch();
        if ($o && in_array($o['status'],['completed','pending'])) {
            $db->beginTransaction();
            try {
                $db->prepare("UPDATE users SET balance=balance+? WHERE id=?")->execute([$o['total_price'],$o['user_id']]);
                $db->prepare("UPDATE card_orders SET status='refunded', note='Admin refunded' WHERE id=?")->execute([$orderId]);
                if ($o['pin_id']) {
                    $db->prepare("UPDATE card_pins SET status='available', sold_to=NULL, sold_at=NULL, order_id=NULL WHERE id=?")->execute([$o['pin_id']]);
                    $cardId = $o['card_id'];
                    $stock = $db->prepare("SELECT COUNT(*) FROM card_pins WHERE card_id=? AND status='available'");
                    $stock->execute([$cardId]);
                    $db->prepare("UPDATE cards SET stock=? WHERE id=?")->execute([$stock->fetchColumn(), $cardId]);
                }
                $db->commit();
                $msg = ['ok'=>true,'text'=>'Refunded!'];
                header('Location: cards.php?ok=1'); exit;
            } catch(Exception $e) { $db->rollBack(); $msg=['ok'=>false,'text'=>$e->getMessage()]; }
        }
    }
}

// Load data
$categories = $db->query("SELECT c.*, (SELECT COUNT(*) FROM cards WHERE category_id=c.id AND is_active=1) as card_count FROM card_categories c ORDER BY sort_order, id")->fetchAll();
$allCards   = $db->query("SELECT cd.*, cc.name as cat_name, cc.color as cat_color, (SELECT COUNT(*) FROM card_pins WHERE card_id=cd.id AND status='available') as avail_pins FROM cards cd JOIN card_categories cc ON cd.category_id=cc.id ORDER BY cd.category_id, cd.sort_order, cd.id")->fetchAll();
$orders     = $db->query("SELECT o.*, u.name as uname, c.name as card_name FROM card_orders o JOIN users u ON o.user_id=u.id JOIN cards c ON o.card_id=c.id ORDER BY o.created_at DESC LIMIT 50")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Cards Manager — Admin</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
:root{--primary:#1a3c8f;--dark:#0d1f4e;--success:#38a169;--danger:#e53e3e;--warn:#d69e2e}
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Segoe UI',sans-serif;background:#f5f7fa;min-height:100vh}
.admin-wrap{display:flex;min-height:100vh}
.content{flex:1;padding:24px;max-width:1200px}
h1{font-size:22px;font-weight:800;color:var(--dark);margin-bottom:20px;display:flex;align-items:center;gap:10px}

/* Tabs */
.tabs{display:flex;gap:6px;margin-bottom:20px;flex-wrap:wrap}
.tab{padding:9px 18px;border-radius:10px;border:2px solid #e8ecf4;background:white;cursor:pointer;font-size:13px;font-weight:700;color:#555;transition:0.2s}
.tab.active{background:var(--primary);border-color:var(--primary);color:white}

/* Section */
.section{display:none}.section.active{display:block}

/* Card grid */
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:14px;margin-bottom:20px}
.card-box{background:white;border-radius:16px;overflow:hidden;box-shadow:0 2px 12px rgba(0,0,0,0.06);transition:0.2s}
.card-box:hover{box-shadow:0 4px 20px rgba(0,0,0,0.1)}
.card-img{width:100%;height:140px;object-fit:cover;background:#f0f4ff;display:flex;align-items:center;justify-content:center;font-size:48px}
.card-img img{width:100%;height:100%;object-fit:cover}
.card-body{padding:14px}
.card-cat-badge{display:inline-block;padding:2px 8px;border-radius:20px;font-size:10px;font-weight:700;margin-bottom:6px}
.card-name{font-size:14px;font-weight:800;color:var(--dark);margin-bottom:4px}
.card-meta{font-size:11px;color:#888;margin-bottom:8px}
.card-price-row{display:flex;align-items:center;gap:8px;margin-bottom:10px}
.card-price{font-size:18px;font-weight:800;color:var(--primary)}
.card-orig{font-size:12px;color:#aaa;text-decoration:line-through}
.card-stock{font-size:11px;font-weight:700;padding:2px 8px;border-radius:20px}
.stock-ok{background:#f0fff4;color:#276749}
.stock-low{background:#fffaf0;color:#d69e2e}
.stock-empty{background:#fff5f5;color:#c53030}
.card-actions{display:flex;gap:6px}
.btn{padding:7px 12px;border:none;border-radius:8px;font-size:12px;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:5px}
.btn-primary{background:var(--primary);color:white}
.btn-success{background:var(--success);color:white}
.btn-danger{background:var(--danger);color:white}
.btn-warn{background:var(--warn);color:white}
.btn-gray{background:#f0f0f0;color:#555}
.btn-outline{background:white;border:2px solid var(--primary);color:var(--primary)}
.btn-lg{padding:11px 20px;font-size:14px;border-radius:12px}

/* Cat grid */
.cat-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:12px;margin-bottom:20px}
.cat-card{background:white;border-radius:14px;overflow:hidden;box-shadow:0 2px 10px rgba(0,0,0,0.06)}
.cat-header{padding:20px;text-align:center}
.cat-icon-big{font-size:36px;margin-bottom:8px;display:block}
.cat-title{font-size:15px;font-weight:800;color:var(--dark)}
.cat-sub{font-size:11px;color:#888;margin-top:3px}
.cat-footer{padding:10px 14px;border-top:1px solid #f0f0f0;display:flex;gap:6px;justify-content:flex-end}

/* Add button */
.add-fab{background:var(--primary);color:white;border:none;padding:10px 20px;border-radius:12px;font-size:14px;font-weight:700;cursor:pointer;display:flex;align-items:center;gap:8px;margin-bottom:16px}

/* Modal */
.modal-ov{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:1000;align-items:center;justify-content:center;padding:20px}
.modal-ov.open{display:flex}
.modal-box{background:white;border-radius:20px;width:100%;max-width:520px;max-height:90vh;overflow-y:auto;padding:24px}
.modal-box h3{font-size:18px;font-weight:800;margin-bottom:18px;display:flex;align-items:center;gap:8px}
.fg{margin-bottom:14px}
.fg label{display:block;font-size:12px;font-weight:700;color:#555;text-transform:uppercase;letter-spacing:0.4px;margin-bottom:6px}
.fg input,.fg textarea,.fg select{width:100%;padding:11px 14px;border:2px solid #e8ecf4;border-radius:10px;font-size:14px;outline:none;font-family:inherit}
.fg input:focus,.fg textarea:focus,.fg select:focus{border-color:var(--primary)}
.fg textarea{resize:vertical;min-height:80px}
.frow{display:grid;gap:10px}
.frow-2{grid-template-columns:1fr 1fr}
.frow-3{grid-template-columns:1fr 1fr 1fr}
.img-preview{margin-top:8px;border-radius:10px;overflow:hidden;max-height:120px;background:#f0f4ff;display:flex;align-items:center;justify-content:center}
.img-preview img{max-height:120px;max-width:100%;object-fit:contain}
.modal-footer{display:flex;gap:8px;justify-content:flex-end;margin-top:18px;padding-top:14px;border-top:1px solid #f0f0f0}

/* Orders table */
.tbl{width:100%;border-collapse:collapse;background:white;border-radius:14px;overflow:hidden;box-shadow:0 2px 10px rgba(0,0,0,0.05)}
.tbl th{background:#f8fafc;padding:12px 14px;text-align:left;font-size:11px;font-weight:700;color:#888;text-transform:uppercase}
.tbl td{padding:12px 14px;font-size:13px;border-top:1px solid #f5f5f5}
.badge{padding:3px 10px;border-radius:20px;font-size:11px;font-weight:700}
.badge-completed{background:#f0fff4;color:#276749}
.badge-pending{background:#fffaf0;color:#d69e2e}
.badge-failed,.badge-refunded{background:#fff5f5;color:#c53030}

/* Pin list */
.pin-list{display:flex;flex-direction:column;gap:6px;max-height:200px;overflow-y:auto;margin-top:8px}
.pin-item{background:#f8fafc;border-radius:8px;padding:8px 12px;display:flex;align-items:center;justify-content:space-between;font-family:monospace;font-size:13px}
.pin-status{font-size:10px;font-weight:700;padding:2px 6px;border-radius:10px}
.pin-avail{background:#f0fff4;color:#276749}
.pin-sold{background:#f0f0f0;color:#888}

/* Alert */
.alert{padding:12px 16px;border-radius:12px;margin-bottom:16px;font-size:13px;font-weight:600;display:flex;align-items:center;gap:8px}
.alert-ok{background:#f0fff4;color:#276749;border:1px solid #c6f6d5}
.alert-err{background:#fff5f5;color:#c53030;border:1px solid #fed7d7}

.empty{text-align:center;padding:40px;color:#aaa}
.empty i{font-size:36px;display:block;margin-bottom:10px;color:#ddd}
</style>
</head>
<body>
<div class="admin-wrap">
<?php include 'includes/admin_sidebar.php' ?? ''; ?>
<div class="content">
<h1><i class="fas fa-layer-group" style="color:var(--primary)"></i> Cards Manager</h1>

<?php if($msg): ?>
<div class="alert <?= $msg['ok']?'alert-ok':'alert-err' ?>">
    <?= $msg['ok']?'✅':'❌' ?> <?= htmlspecialchars($msg['text']) ?>
</div>
<?php endif; ?>

<!-- Tabs -->
<div class="tabs">
    <div class="tab active" onclick="switchTab('categories',this)"><i class="fas fa-th-large"></i> Categories</div>
    <div class="tab" onclick="switchTab('cards',this)"><i class="fas fa-layer-group"></i> Cards</div>
    <div class="tab" onclick="switchTab('pins',this)"><i class="fas fa-key"></i> PINs / Inventory</div>
    <div class="tab" onclick="switchTab('orders',this)"><i class="fas fa-shopping-bag"></i> Orders (<?= count($orders) ?>)</div>
</div>

<!-- CATEGORIES -->
<div class="section active" id="sec-categories">
    <button class="add-fab" onclick="openCatModal()"><i class="fas fa-plus"></i> Add Category</button>
    <?php if(empty($categories)): ?>
    <div class="empty"><i class="fas fa-th-large"></i> No categories yet</div>
    <?php else: ?>
    <div class="cat-grid">
    <?php foreach($categories as $cat): ?>
    <div class="cat-card">
        <div class="cat-header" style="background:<?= $cat['color'] ?>18;border-bottom:3px solid <?= $cat['color'] ?>">
            <?php if($cat['image']): ?>
            <img src="../<?= htmlspecialchars($cat['image']) ?>" style="width:60px;height:60px;object-fit:contain;border-radius:10px;margin-bottom:8px">
            <?php else: ?>
            <span class="cat-icon-big"><?= $cat['icon'] ?></span>
            <?php endif; ?>
            <div class="cat-title"><?= htmlspecialchars($cat['name']) ?></div>
            <div class="cat-sub"><?= $cat['card_count'] ?> cards <?= $cat['is_active']?'<span style="color:#38a169">●</span>':'<span style="color:#e53e3e">●</span>' ?></div>
        </div>
        <div class="cat-footer">
            <button class="btn btn-primary" onclick='openCatModal(<?= htmlspecialchars(json_encode($cat),ENT_QUOTES) ?>)'><i class="fas fa-edit"></i></button>
            <form method="POST" style="display:inline"><input type="hidden" name="action" value="cat_toggle"><input type="hidden" name="cat_id" value="<?= $cat['id'] ?>"><button type="submit" class="btn btn-gray"><?= $cat['is_active']?'Disable':'Enable' ?></button></form>
            <form method="POST" style="display:inline" onsubmit="return confirm('Delete category?')"><input type="hidden" name="action" value="cat_delete"><input type="hidden" name="cat_id" value="<?= $cat['id'] ?>"><button type="submit" class="btn btn-danger"><i class="fas fa-trash"></i></button></form>
        </div>
    </div>
    <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<!-- CARDS -->
<div class="section" id="sec-cards">
    <button class="add-fab" onclick="openCardModal()"><i class="fas fa-plus"></i> Add Card</button>
    <?php if(empty($allCards)): ?>
    <div class="empty"><i class="fas fa-layer-group"></i> No cards yet. Add categories first.</div>
    <?php else: ?>
    <div class="grid">
    <?php foreach($allCards as $c): 
        $stockClass = $c['avail_pins']>5?'stock-ok':($c['avail_pins']>0?'stock-low':'stock-empty');
    ?>
    <div class="card-box">
        <div class="card-img">
            <?php if($c['image']): ?><img src="../<?= htmlspecialchars($c['image']) ?>" alt=""><?php else: ?><span>🎴</span><?php endif; ?>
        </div>
        <div class="card-body">
            <div class="card-cat-badge" style="background:<?= $c['cat_color'] ?>22;color:<?= $c['cat_color'] ?>"><?= htmlspecialchars($c['cat_name']) ?></div>
            <div class="card-name"><?= htmlspecialchars($c['name']) ?></div>
            <div class="card-meta">
                <?= $c['validity']?'⏱ '.$c['validity'].' &nbsp;':'' ?>
                <?= $c['region']?'🌍 '.$c['region']:'' ?>
            </div>
            <div class="card-price-row">
                <span class="card-price">৳<?= number_format($c['price'],2) ?></span>
                <?php if($c['original_price']): ?><span class="card-orig">৳<?= number_format($c['original_price'],2) ?></span><?php endif; ?>
                <span class="card-stock <?= $stockClass ?>"><?= $c['avail_pins'] ?> left</span>
            </div>
            <div class="card-actions">
                <button class="btn btn-primary" onclick='openCardModal(<?= htmlspecialchars(json_encode($c),ENT_QUOTES) ?>)'><i class="fas fa-edit"></i> Edit</button>
                <button class="btn btn-success" onclick="openPinModal(<?= $c['id'] ?>,'<?= addslashes($c['name']) ?>')"><i class="fas fa-key"></i> PINs</button>
                <form method="POST" style="display:inline"><input type="hidden" name="action" value="card_toggle"><input type="hidden" name="card_id" value="<?= $c['id'] ?>"><button type="submit" class="btn btn-gray"><?= $c['is_active']?'Off':'On' ?></button></form>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<!-- PINS -->
<div class="section" id="sec-pins">
    <div style="margin-bottom:14px">
        <select id="pinCardFilter" onchange="filterPins()" style="padding:10px 14px;border:2px solid #e8ecf4;border-radius:10px;font-size:14px;outline:none;min-width:220px">
            <option value="">All Cards</option>
            <?php foreach($allCards as $c): ?>
            <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['name']) ?> (<?= $c['avail_pins'] ?> avail)</option>
            <?php endforeach; ?>
        </select>
    </div>
    <?php
    // Load all pins
    $allPins = $db->query("SELECT p.*, c.name as card_name, c.category_id FROM card_pins p JOIN cards c ON p.card_id=c.id ORDER BY p.card_id, p.status, p.created_at DESC LIMIT 200")->fetchAll();
    if(empty($allPins)):
    ?>
    <div class="empty"><i class="fas fa-key"></i> No PINs added yet</div>
    <?php else: ?>
    <table class="tbl">
        <thead><tr><th>Card</th><th>PIN Code</th><th>Serial</th><th>Status</th><th>Added</th><th>Action</th></tr></thead>
        <tbody>
        <?php foreach($allPins as $p): ?>
        <tr data-card="<?= $p['card_id'] ?>">
            <td style="font-size:12px;color:#666"><?= htmlspecialchars($p['card_name']) ?></td>
            <td><span style="font-family:monospace;font-size:13px;font-weight:700"><?= htmlspecialchars(substr($p['pin_code'],0,20)).(strlen($p['pin_code'])>20?'...':'') ?></span></td>
            <td style="font-size:12px;color:#888"><?= htmlspecialchars($p['serial_number']??'—') ?></td>
            <td><span class="pin-status <?= $p['status']==='available'?'pin-avail':'pin-sold' ?>"><?= ucfirst($p['status']) ?></span></td>
            <td style="font-size:11px;color:#aaa"><?= date('d M, h:i A',strtotime($p['created_at'])) ?></td>
            <td>
                <?php if($p['status']==='available'): ?>
                <form method="POST" onsubmit="return confirm('Delete PIN?')">
                    <input type="hidden" name="action" value="pin_delete">
                    <input type="hidden" name="pin_id" value="<?= $p['id'] ?>">
                    <input type="hidden" name="pin_card_id" value="<?= $p['card_id'] ?>">
                    <button type="submit" class="btn btn-danger" style="padding:5px 10px"><i class="fas fa-trash"></i></button>
                </form>
                <?php else: ?>
                <span style="font-size:11px;color:#aaa">Sold</span>
                <?php endif; ?>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>
</div>

<!-- ORDERS -->
<div class="section" id="sec-orders">
    <?php if(empty($orders)): ?>
    <div class="empty"><i class="fas fa-shopping-bag"></i> No orders yet</div>
    <?php else: ?>
    <table class="tbl">
        <thead><tr><th>Ref</th><th>User</th><th>Card</th><th>Price</th><th>Status</th><th>Date</th><th>Action</th></tr></thead>
        <tbody>
        <?php foreach($orders as $o): ?>
        <tr>
            <td style="font-family:monospace;font-size:12px"><?= htmlspecialchars($o['reference']??'—') ?></td>
            <td><?= htmlspecialchars($o['uname']) ?></td>
            <td style="font-size:12px"><?= htmlspecialchars($o['card_name']) ?></td>
            <td style="font-weight:700;color:var(--primary)">৳<?= number_format($o['total_price'],2) ?></td>
            <td><span class="badge badge-<?= $o['status'] ?>"><?= ucfirst($o['status']) ?></span></td>
            <td style="font-size:11px;color:#aaa"><?= date('d M, h:i A',strtotime($o['created_at'])) ?></td>
            <td>
                <?php if(in_array($o['status'],['completed','pending'])): ?>
                <form method="POST" onsubmit="return confirm('Refund?')">
                    <input type="hidden" name="action" value="order_refund">
                    <input type="hidden" name="order_id" value="<?= $o['id'] ?>">
                    <button type="submit" class="btn btn-warn" style="padding:5px 10px"><i class="fas fa-undo"></i></button>
                </form>
                <?php endif; ?>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>
</div>

</div><!-- content -->
</div><!-- wrap -->

<!-- Category Modal -->
<div class="modal-ov" id="catModal">
<div class="modal-box">
    <h3 id="catModalTitle"><i class="fas fa-th-large" style="color:var(--primary)"></i> Add Category</h3>
    <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="action" value="cat_save">
        <input type="hidden" name="cat_id" id="catId">
        <input type="hidden" name="cat_existing_img" id="catExistImg">
        <div class="frow frow-2">
            <div class="fg"><label>Name *</label><input name="cat_name" id="catName" required placeholder="Netflix"></div>
            <div class="fg"><label>Icon (emoji)</label><input name="cat_icon" id="catIcon" placeholder="🎬" style="font-size:20px;text-align:center;width:70px"></div>
        </div>
        <div class="frow frow-2">
            <div class="fg"><label>Color</label><input type="color" name="cat_color" id="catColor" value="#E50914" style="height:42px;padding:4px;width:60px"></div>
            <div class="fg"><label>Sort Order</label><input type="number" name="cat_sort" id="catSort" value="0"></div>
        </div>
        <div class="fg"><label>Description</label><textarea name="cat_desc" id="catDesc" placeholder="Category description..."></textarea></div>
        <div class="fg">
            <label>Image (optional)</label>
            <input type="file" name="cat_image" accept="image/*" onchange="previewImg(this,'catImgPreview')">
            <div class="img-preview" id="catImgPreview"></div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-gray btn-lg" onclick="closeCatModal()">Cancel</button>
            <button type="submit" class="btn btn-primary btn-lg"><i class="fas fa-save"></i> Save</button>
        </div>
    </form>
</div>
</div>

<!-- Card Modal -->
<div class="modal-ov" id="cardModal">
<div class="modal-box">
    <h3 id="cardModalTitle"><i class="fas fa-layer-group" style="color:var(--primary)"></i> Add Card</h3>
    <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="action" value="card_save">
        <input type="hidden" name="card_id" id="cardId">
        <input type="hidden" name="card_existing_img" id="cardExistImg">
        <div class="fg">
            <label>Category *</label>
            <select name="card_cat" id="cardCat" required>
                <option value="">Select category</option>
                <?php foreach($categories as $cat): ?>
                <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="fg"><label>Card Name *</label><input name="card_name" id="cardName" required placeholder="Netflix 1 Month (BD)"></div>
        <div class="fg"><label>Description</label><textarea name="card_desc" id="cardDesc" placeholder="Card description, instructions..."></textarea></div>
        <div class="frow frow-2">
            <div class="fg"><label>Sale Price (৳) *</label><input type="number" step="0.01" name="card_price" id="cardPrice" required placeholder="0.00"></div>
            <div class="fg"><label>Commission (৳) <span style="font-size:10px;color:#888">API/reseller commission</span></label><input type="number" step="0.01" name="card_commission" id="cardCommission" placeholder="0.00" value="0"></div>
            <div class="fg"><label>Original Price (৳)</label><input type="number" step="0.01" name="card_orig_price" id="cardOrigPrice" placeholder="0.00"></div>
        </div>
        <div class="frow frow-2">
            <div class="fg"><label>Validity</label><input name="card_validity" id="cardValidity" placeholder="1 Month / 30 Days"></div>
            <div class="fg"><label>Region</label><input name="card_region" id="cardRegion" placeholder="Bangladesh / Global"></div>
        </div>
        <div class="fg">
            <label>Card Image</label>
            <input type="file" name="card_image" accept="image/*" onchange="previewImg(this,'cardImgPreview')">
            <div class="img-preview" id="cardImgPreview"></div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-gray btn-lg" onclick="closeCardModal()">Cancel</button>
            <button type="submit" class="btn btn-primary btn-lg"><i class="fas fa-save"></i> Save</button>
        </div>
    </form>
</div>
</div>

<!-- PIN Modal -->
<div class="modal-ov" id="pinModal">
<div class="modal-box">
    <h3><i class="fas fa-key" style="color:var(--success)"></i> <span id="pinModalTitle">Manage PINs</span></h3>

    <!-- Upload Method Tabs -->
    <div style="display:flex;gap:0;background:#f5f7fa;border-radius:10px;padding:3px;margin-bottom:16px">
        <div id="ptab-manual" onclick="switchPinTab('manual')" style="flex:1;padding:8px;text-align:center;border-radius:8px;cursor:pointer;font-size:13px;font-weight:700;background:white;color:var(--primary);box-shadow:0 1px 4px rgba(0,0,0,0.08)">✏️ Manual</div>
        <div id="ptab-excel" onclick="switchPinTab('excel')" style="flex:1;padding:8px;text-align:center;border-radius:8px;cursor:pointer;font-size:13px;font-weight:700;color:#888">📊 Excel/CSV</div>
    </div>

    <!-- Manual Form -->
    <form method="POST" enctype="multipart/form-data" id="pinFormManual">
        <input type="hidden" name="action" value="pin_add">
        <input type="hidden" name="pin_card_id" id="pinCardId">
        <div class="fg">
            <label>PIN Codes * (one per line)</label>
            <textarea name="pin_codes" rows="6" placeholder="XXXX-XXXX-XXXX&#10;YYYY-YYYY-YYYY&#10;&#10;Or pipe-separated:&#10;PIN|Serial|Extra&#10;ABCD-1234|SN001|Expires Dec 2025"></textarea>
            <div style="font-size:11px;color:#888;margin-top:4px">
                একটা line = একটা PIN &nbsp;|&nbsp; অথবা <code>PIN|Serial|Extra</code> format
            </div>
        </div>
        <div class="frow frow-2">
            <div class="fg"><label>Serial (সব PIN এর জন্য)</label><input name="pin_serial" placeholder="Optional"></div>
            <div class="fg"><label>Extra Info</label><input name="pin_extra" placeholder="Expiry, notes..."></div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-gray btn-lg" onclick="closePinModal()">Cancel</button>
            <button type="submit" class="btn btn-success btn-lg"><i class="fas fa-plus"></i> Add PINs</button>
        </div>
    </form>

    <!-- Excel/CSV Form -->
    <form method="POST" enctype="multipart/form-data" id="pinFormExcel" style="display:none">
        <input type="hidden" name="action" value="pin_add">
        <input type="hidden" name="pin_card_id" id="pinCardId2">

        <!-- Template download -->
        <div style="background:#f0f4ff;border-radius:12px;padding:14px;margin-bottom:16px">
            <div style="font-size:13px;font-weight:700;color:var(--primary);margin-bottom:8px">📋 Excel Template Format</div>
            <div style="font-family:monospace;font-size:12px;background:white;border-radius:8px;padding:10px;border:1px solid #e8ecf4;color:#555">
                <div style="color:#888;margin-bottom:4px">pin_code &nbsp;&nbsp;| serial_number | extra_info</div>
                <div>XXXX-XXXX &nbsp;| SN001 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| Expires Jan 2026</div>
                <div>YYYY-YYYY &nbsp;| SN002 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| Expires Jan 2026</div>
            </div>
            <button type="button" onclick="downloadTemplate()" style="margin-top:10px;background:var(--primary);color:white;border:none;padding:8px 16px;border-radius:8px;font-size:12px;font-weight:700;cursor:pointer;display:flex;align-items:center;gap:6px">
                <i class="fas fa-download"></i> Download Template CSV
            </button>
        </div>

        <div class="fg">
            <label>CSV File Upload *</label>
            <input type="file" name="pin_excel" id="pinExcelFile" accept=".csv" required onchange="previewCsv(this)">
            <div style="font-size:11px;color:#888;margin-top:4px">
                ⚠️ Excel (.xlsx) → File → Save As → <b>CSV (Comma delimited)</b> করে upload করুন
            </div>
        </div>

        <div id="csvPreview" style="display:none;background:#f8fafc;border-radius:10px;padding:12px;margin-top:8px;font-size:12px;color:#555;max-height:150px;overflow-y:auto"></div>

        <div class="modal-footer">
            <button type="button" class="btn btn-gray btn-lg" onclick="closePinModal()">Cancel</button>
            <button type="submit" class="btn btn-success btn-lg"><i class="fas fa-upload"></i> Upload PINs</button>
        </div>
    </form>
</div>
</div>

<script>
function switchTab(tab, el) {
    document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
    document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));
    el.classList.add('active');
    document.getElementById('sec-'+tab).classList.add('active');
}

function openCatModal(cat) {
    document.getElementById('catModalTitle').innerHTML = '<i class="fas fa-th-large" style="color:var(--primary)"></i> '+(cat?'Edit':'Add')+' Category';
    document.getElementById('catId').value = cat?.id||'';
    document.getElementById('catName').value = cat?.name||'';
    document.getElementById('catIcon').value = cat?.icon||'🎴';
    document.getElementById('catColor').value = cat?.color||'#1a3c8f';
    document.getElementById('catSort').value = cat?.sort_order||0;
    document.getElementById('catDesc').value = cat?.description||'';
    document.getElementById('catExistImg').value = cat?.image||'';
    const prev = document.getElementById('catImgPreview');
    prev.innerHTML = cat?.image ? '<img src="../'+cat.image+'">' : '';
    document.getElementById('catModal').classList.add('open');
}
function closeCatModal(){ document.getElementById('catModal').classList.remove('open'); }

function openCardModal(card) {
    document.getElementById('cardModalTitle').innerHTML = '<i class="fas fa-layer-group" style="color:var(--primary)"></i> '+(card?'Edit':'Add')+' Card';
    document.getElementById('cardId').value = card?.id||'';
    document.getElementById('cardCat').value = card?.category_id||'';
    document.getElementById('cardName').value = card?.name||'';
    document.getElementById('cardDesc').value = card?.description||'';
    document.getElementById('cardPrice').value = card?.price||'';
    document.getElementById('cardOrigPrice').value = card?.original_price||'';
    document.getElementById('cardCommission').value = card?.commission||'';
    document.getElementById('cardValidity').value = card?.validity||'';
    document.getElementById('cardRegion').value = card?.region||'';
    document.getElementById('cardExistImg').value = card?.image||'';
    const prev = document.getElementById('cardImgPreview');
    prev.innerHTML = card?.image ? '<img src="../'+card.image+'">' : '';
    document.getElementById('cardModal').classList.add('open');
}
function closeCardModal(){ document.getElementById('cardModal').classList.remove('open'); }

function openPinModal(cardId, cardName) {
    document.getElementById('pinCardId').value = cardId;
    document.getElementById('pinCardId2').value = cardId;
    document.getElementById('pinModalTitle').textContent = cardName + ' — PINs';
    switchPinTab('manual');
    document.getElementById('pinModal').classList.add('open');
}
function closePinModal(){ document.getElementById('pinModal').classList.remove('open'); }

function switchPinTab(tab) {
    document.getElementById('pinFormManual').style.display = tab==='manual' ? '' : 'none';
    document.getElementById('pinFormExcel').style.display  = tab==='excel'  ? '' : 'none';
    const mTab = document.getElementById('ptab-manual');
    const eTab = document.getElementById('ptab-excel');
    if(tab==='manual') {
        mTab.style.background='white'; mTab.style.color='var(--primary)'; mTab.style.boxShadow='0 1px 4px rgba(0,0,0,0.08)';
        eTab.style.background=''; eTab.style.color='#888'; eTab.style.boxShadow='';
    } else {
        eTab.style.background='white'; eTab.style.color='var(--primary)'; eTab.style.boxShadow='0 1px 4px rgba(0,0,0,0.08)';
        mTab.style.background=''; mTab.style.color='#888'; mTab.style.boxShadow='';
    }
}

function previewCsv(input) {
    const file = input.files[0];
    if(!file) return;
    const reader = new FileReader();
    reader.onload = e => {
        const lines = e.target.result.split('\n').slice(0,8);
        const prev = document.getElementById('csvPreview');
        let html = '<b style="color:#555">Preview (first 8 rows):</b><br><br>';
        lines.forEach((line,i) => {
            if(!line.trim()) return;
            const cols = line.split(',');
            const pin = cols[0]||''; const serial = cols[1]||''; const extra = cols[2]||'';
            const isHeader = i===0 && pin.toLowerCase().includes('pin');
            html += `<div style="padding:3px 0;border-bottom:1px solid #eee;${isHeader?'color:#aaa;font-style:italic':''}">
                <span style="font-family:monospace;font-weight:700">${pin}</span>
                ${serial?` <span style="color:#888">| ${serial}</span>`:''}
                ${extra?` <span style="color:#aaa">| ${extra}</span>`:''}
            </div>`;
        });
        prev.innerHTML = html;
        prev.style.display = 'block';
    };
    reader.readAsText(file);
}

function downloadTemplate() {
    const csv = "pin_code,serial_number,extra_info\nXXXX-XXXX-XXXX,SN001,Expires Jan 2026\nYYYY-YYYY-YYYY,SN002,Expires Jan 2026\nZZZZ-ZZZZ-ZZZZ,,\n";
    const blob = new Blob([csv], {type:'text/csv'});
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = 'card_pins_template.csv';
    a.click();
}

function previewImg(input, previewId) {
    const prev = document.getElementById(previewId);
    if(input.files && input.files[0]) {
        const r = new FileReader();
        r.onload = e => prev.innerHTML = '<img src="'+e.target.result+'">';
        r.readAsDataURL(input.files[0]);
    }
}

function filterPins() {
    const cardId = document.getElementById('pinCardFilter').value;
    document.querySelectorAll('#sec-pins tbody tr').forEach(tr => {
        tr.style.display = (!cardId || tr.dataset.card === cardId) ? '' : 'none';
    });
}

// Close modals on overlay click
['catModal','cardModal','pinModal'].forEach(id => {
    document.getElementById(id).addEventListener('click', function(e) {
        if(e.target === this) this.classList.remove('open');
    });
});
</script>
</body>
</html>
