<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}
global $pdo;
$message = '';

// ==================================================
// AUTO-FIX: Create column if it doesn't exist
// ==================================================
try {
    $pdo->exec("ALTER TABLE `vip_levels` ADD `level_up_bonus` DECIMAL(10,2) NOT NULL DEFAULT '0.00'");
} catch (PDOException $e) {
    // Agar column pehle se hoga toh error ko ignore kar dega
}

// ==================================================
// 1. AJAX IMAGE UPLOAD LOGIC (For Visual Editor)
// ==================================================
if (isset($_POST['ajax_upload'])) {
    $targetDir = '../assets/png/'; 
    if (!is_dir($targetDir)) { mkdir($targetDir, 0777, true); }

    $filename = $_POST['target_filename'];
    $file = $_FILES['vip_image'];

    if ($file['error'] === 0) {
        $targetPath = $targetDir . $filename;
        if (move_uploaded_file($file['tmp_name'], $targetPath)) {
            echo json_encode(['success' => true, 'url' => $targetPath . '?v=' . time()]);
        } else {
            echo json_encode(['success' => false, 'msg' => 'Upload failed. Check folder permissions.']);
        }
    } else {
        echo json_encode(['success' => false, 'msg' => 'Invalid file.']);
    }
    exit; 
}

// ==================================================
// 2. BONUS & LEVEL MANAGEMENT LOGIC (Form Submit)
// ==================================================
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_vip'])) {
    $level = (int)$_POST['level'];
    $req_recharge = (float)$_POST['required_recharge'];
    $monthly_bonus = (float)$_POST['monthly_bonus'];
    $level_up_bonus = (float)$_POST['level_up_bonus'];

    try {
        $check = $pdo->prepare("SELECT level FROM vip_levels WHERE level = ?");
        $check->execute([$level]);
        
        if ($check->rowCount() > 0) {
            // Update existing
            $upd = $pdo->prepare("UPDATE vip_levels SET required_recharge=?, monthly_bonus=?, level_up_bonus=? WHERE level=?");
            $upd->execute([$req_recharge, $monthly_bonus, $level_up_bonus, $level]);
            $message = "<div class='p-4 mb-4 text-green-700 bg-green-100 border border-green-300 rounded-lg font-bold'>✅ VIP Level {$level} Bonus Updated!</div>";
        } else {
            // Insert new
            $ins = $pdo->prepare("INSERT INTO vip_levels (level, required_recharge, monthly_bonus, level_up_bonus) VALUES (?, ?, ?, ?)");
            $ins->execute([$level, $req_recharge, $monthly_bonus, $level_up_bonus]);
            $message = "<div class='p-4 mb-4 text-green-700 bg-green-100 border border-green-300 rounded-lg font-bold'>✅ New VIP Level {$level} Added!</div>";
        }
    } catch (Exception $e) {
        $message = "<div class='p-4 mb-4 text-red-700 bg-red-100 border border-red-300 rounded-lg font-bold'>❌ Error: " . $e->getMessage() . "</div>";
    }
}

// Handle Delete
if (isset($_GET['delete'])) {
    $del_level = (int)$_GET['delete'];
    $pdo->prepare("DELETE FROM vip_levels WHERE level = ?")->execute([$del_level]);
    header("Location: vipmanage.php");
    exit;
}

// Fetch All Levels
$levels = [];
try {
    $levels = $pdo->query("SELECT * FROM vip_levels ORDER BY level ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {}

$pageTitle = 'VIP Levels';
require_once 'includes/header.php';
?>
<style>
.mobile-simulator { max-width: 380px; margin: 0 auto; background: #f7f8fa; border-radius: 16px; box-shadow: 0 8px 24px rgba(0,0,0,0.1); overflow: hidden; border: 6px solid #333; }
.img-upload-box { position: relative; cursor: pointer; display: inline-block; border: 2px dashed transparent; transition: 0.3s; }
.img-upload-box:hover { border-color: #009ef7; border-radius: 8px; }
.img-upload-box .overlay { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.6); color: #fff; display: flex; align-items: center; justify-content: center; font-size: 11px; font-weight: bold; opacity: 0; transition: 0.3s; border-radius: 8px; }
.img-upload-box:hover .overlay { opacity: 1; }
.uploading::after { content: 'Uploading...'; position: absolute; inset: 0; background: rgba(0,158,247,0.9); color: white; display: flex; align-items: center; justify-content: center; font-size: 11px; font-weight: bold; border-radius: 8px;}
.vip-card { border: 1px solid #ebedf0; border-radius: 10px; overflow: hidden; }
.vip-card-head { background: linear-gradient(135deg, #FF9A9E 0%, #FECFEF 100%); height: 75px; display: flex; align-items: center; justify-content: center; }
.vip-card-head.orange { background: linear-gradient(135deg, #f6d365 0%, #fda085 100%); }
</style>
<?php if($message): ?><div class="alert alert-success fw-bold mb-4"><?= $message ?></div><?php endif; ?>
<div class="row g-4">

    <div class="col-lg-8">
        <div class="custom-card">
            <div class="custom-card-header"><i class="fas fa-star me-2"></i> Add / Edit VIP Level</div>
            <div class="p-4">
                <form method="POST" class="row g-3 align-items-end">
                    <div class="col-md-2"><label class="form-label small fw-bold">VIP Level</label><input type="number" name="level" required class="form-control"></div>
                    <div class="col-md-2"><label class="form-label small fw-bold">Required EXP</label><input type="number" step="0.01" name="required_recharge" required class="form-control"></div>
                    <div class="col-md-2"><label class="form-label small fw-bold">Level Up Bonus (₹)</label><input type="number" step="0.01" name="level_up_bonus" required class="form-control"></div>
                    <div class="col-md-2"><label class="form-label small fw-bold">Monthly Bonus (₹)</label><input type="number" step="0.01" name="monthly_bonus" required class="form-control"></div>
                    <div class="col-md-2"><button type="submit" name="save_vip" class="btn btn-primary w-100 fw-bold">Save</button></div>
                </form>
            </div>
        </div>
        <div class="custom-card">
            <div class="custom-card-header"><i class="fas fa-list me-2"></i> Current VIP Levels</div>
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="table-light"><tr><th>VIP Level</th><th>Required EXP</th><th>Level Up Bonus</th><th>Monthly Bonus</th><th class="text-center">Action</th></tr></thead>
                    <tbody>
                        <?php if(empty($levels)): ?>
                            <tr><td colspan="5" class="text-center py-4 text-muted">No VIP levels. Add above.</td></tr>
                        <?php else: foreach($levels as $row): ?>
                            <tr>
                                <td class="fw-bold text-danger">VIP <?= $row['level'] ?></td>
                                <td><?= number_format($row['required_recharge'] ?? 0, 2) ?> EXP</td>
                                <td class="text-success fw-bold">₹<?= number_format($row['level_up_bonus'] ?? 0, 2) ?></td>
                                <td class="text-primary fw-bold">₹<?= number_format($row['monthly_bonus'] ?? 0, 2) ?></td>
                                <td class="text-center"><a href="?delete=<?= $row['level'] ?>" onclick="return confirm('Delete VIP <?= $row['level'] ?>?');" class="btn btn-sm btn-outline-danger">Delete</a></td>
                            </tr>
                        <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="custom-card">
            <div class="custom-card-header"><i class="fas fa-image me-2"></i> Visual Image Editor</div>
            <div class="p-4">
                    <p class="text-xs text-center text-gray-500 mb-4">Click any image inside the phone to change it live.</p>
                    
                    <div class="mobile-simulator">
                        <div style="background: linear-gradient(180deg, #FF6C6B 0%, #FF4A4A 100%); padding: 15px; color: white; text-align: center; font-weight: bold; font-size: 14px;">
                            Click Icons to Edit
                        </div>

                        <div style="background: #fff; margin: 15px; border-radius: 10px; padding: 15px;">
                            <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 15px; border-bottom: 1px solid #eee; padding-bottom: 10px;">
                                <label class="img-upload-box">
                                    <img id="img_level_up" src="../assets/png/1-fd9896f4.webp" style="width: 40px; height: 40px; object-fit:contain;" onerror="this.src='https://via.placeholder.com/40'">
                                    <div class="overlay">Upload</div>
                                    <input type="file" accept="image/*" hidden onchange="uploadFile(this, '1-fd9896f4.webp', 'img_level_up')">
                                </label>
                                <div style="flex:1; margin-left: 10px;">
                                    <h2 style="font-size: 13px; color: #333; font-weight: bold;">Level up rewards</h2>
                                </div>
                            </div>

                            <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 15px; border-bottom: 1px solid #eee; padding-bottom: 10px;">
                                <label class="img-upload-box">
                                    <img id="img_monthly" src="../assets/png/2-0a41a908.webp" style="width: 40px; height: 40px; object-fit:contain;" onerror="this.src='https://via.placeholder.com/40'">
                                    <div class="overlay">Upload</div>
                                    <input type="file" accept="image/*" hidden onchange="uploadFile(this, '2-0a41a908.webp', 'img_monthly')">
                                </label>
                                <div style="flex:1; margin-left: 10px;">
                                    <h2 style="font-size: 13px; color: #333; font-weight: bold;">Monthly reward</h2>
                                </div>
                            </div>

                            <div style="display: flex; align-items: center; justify-content: space-between;">
                                <label class="img-upload-box">
                                    <img id="img_rebate" src="../assets/png/5-5e6a64b1.webp" style="width: 40px; height: 40px; object-fit:contain;" onerror="this.src='https://via.placeholder.com/40'">
                                    <div class="overlay">Upload</div>
                                    <input type="file" accept="image/*" hidden onchange="uploadFile(this, '5-5e6a64b1.webp', 'img_rebate')">
                                </label>
                                <div style="flex:1; margin-left: 10px;">
                                    <h2 style="font-size: 13px; color: #333; font-weight: bold;">Rebate rate</h2>
                                </div>
                            </div>
                        </div>

                        <div style="background: #fff; margin: 15px; border-radius: 10px; padding: 15px;">
                            <div class="row g-2">
                                <div class="col-6">
                                <div class="vip-card">
                                    <div class="vip-card-head">
                                        <label class="img-upload-box w-full h-full flex justify-center items-center">
                                            <img id="img_card_1" src="../assets/png/welfare1-eee87ee1.webp" style="height: 45px; object-fit:contain;" onerror="this.src='https://via.placeholder.com/45'">
                                            <div class="overlay">Upload</div>
                                            <input type="file" accept="image/*" hidden onchange="uploadFile(this, 'welfare1-eee87ee1.webp', 'img_card_1')">
                                        </label>
                                    </div>
                                    <div class="p-2 text-center small fw-bold">Level up</div>
                                </div>
                                </div>
                                <div class="col-6">
                                <div class="vip-card">
                                    <div class="vip-card-head orange">
                                        <label class="img-upload-box w-full h-full flex justify-center items-center">
                                            <img id="img_card_2" src="../assets/png/welfare2-cf757d28.webp" style="height: 45px; object-fit:contain;" onerror="this.src='https://via.placeholder.com/45'">
                                            <div class="overlay">Upload</div>
                                            <input type="file" accept="image/*" hidden onchange="uploadFile(this, 'welfare2-cf757d28.webp', 'img_card_2')">
                                        </label>
                                    </div>
                                    <div class="p-2 text-center small fw-bold">Monthly</div>
                                </div>
                                </div>
                            </div>
                        </div>

                        <div class="text-center p-3 bg-light rounded mt-2">
                            <span class="small fw-bold text-muted d-block mb-2">Gold Coin Icon</span>
                            <label class="img-upload-box">
                                <img id="img_gold" src="../assets/png/gold-4a60a059.webp" style="width: 30px; height: 30px;" onerror="this.src='https://via.placeholder.com/30'">
                                <div class="overlay">Change</div>
                                <input type="file" accept="image/*" hidden onchange="uploadFile(this, 'gold-4a60a059.webp', 'img_gold')">
                            </label>
                        </div>
            </div>
        </div>
    </div>
</div>

<script>
        function uploadFile(input, targetFilename, imgId) {
            if (input.files && input.files[0]) {
                let file = input.files[0];
                let label = input.closest('.img-upload-box');
                label.classList.add('uploading');

                let formData = new FormData();
                formData.append('ajax_upload', '1');
                formData.append('target_filename', targetFilename);
                formData.append('vip_image', file);

                fetch('', { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => {
                    label.classList.remove('uploading');
                    if (data.success) {
                        document.getElementById(imgId).src = data.url;
                        alert('Image updated live!');
                    } else {
                        alert(data.msg || 'Upload failed');
                    }
                })
                .catch(error => {
                    label.classList.remove('uploading');
                    alert('Network error occurred.');
                });
            }
        }
</script>
<?php require_once 'includes/footer.php'; ?>