<?php
/**
 * Admin - UPI Payment Gateway Settings
 * Manage QR Code, UPI ID, Bonus, Limits
 */
require_once 'includes/header.php';


$message = '';
$messageType = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    // Save UPI Settings
    if ($action === 'save_upi_settings') {
        $settings = [
            'upi_merchant_name' => trim($_POST['upi_merchant_name'] ?? ''),
            'upi_id' => trim($_POST['upi_id'] ?? ''),
            'upi_min_deposit' => (float)($_POST['upi_min_deposit'] ?? 100),
            'upi_max_deposit' => (float)($_POST['upi_max_deposit'] ?? 100000),
            'upi_payment_timeout' => (int)($_POST['upi_payment_timeout'] ?? 600),
            'upi_status' => $_POST['upi_status'] ?? 'active',
        ];
        
        foreach ($settings as $key => $value) {
            $exists = dbFetch("SELECT id FROM settings WHERE setting_key = :key", ['key' => $key]);
            if ($exists) {
                dbUpdate('settings', ['setting_value' => $value], 'setting_key = :key', ['key' => $key]);
            } else {
                dbInsert('settings', ['setting_key' => $key, 'setting_value' => $value]);
            }
        }
        
        $message = 'UPI settings saved successfully!';
        $messageType = 'success';
    }
    
    // Save Bonus Settings
    if ($action === 'save_bonus_settings') {
        $settings = [
            'deposit_bonus_enabled' => isset($_POST['deposit_bonus_enabled']) ? '1' : '0',
            'deposit_bonus_percent' => (float)($_POST['deposit_bonus_percent'] ?? 0),
            'deposit_bonus_min_amount' => (float)($_POST['deposit_bonus_min_amount'] ?? 0),
            'deposit_bonus_max_bonus' => (float)($_POST['deposit_bonus_max_bonus'] ?? 0),
            'bonus_turnover_multiplier' => (float)($_POST['bonus_turnover_multiplier'] ?? 30),
            'cfd_balance_multiplier' => (float)($_POST['cfd_balance_multiplier'] ?? 3),
        ];
        
        foreach ($settings as $key => $value) {
            $exists = dbFetch("SELECT id FROM settings WHERE setting_key = :key", ['key' => $key]);
            if ($exists) {
                dbUpdate('settings', ['setting_value' => $value], 'setting_key = :key', ['key' => $key]);
            } else {
                dbInsert('settings', ['setting_key' => $key, 'setting_value' => $value]);
            }
        }
        
        $message = 'Bonus settings saved successfully!';
        $messageType = 'success';
    }
    
    // Save Bonus Tiers
    if ($action === 'save_bonus_tiers') {
        // Clear existing tiers
        dbQuery("DELETE FROM deposit_bonus_tiers");
        
        $amounts = $_POST['tier_amount'] ?? [];
        $bonuses = $_POST['tier_bonus'] ?? [];
        $types = $_POST['tier_type'] ?? [];
        
        foreach ($amounts as $i => $amount) {
            if ((float)$amount > 0) {
                dbInsert('deposit_bonus_tiers', [
                    'min_amount' => (float)$amount,
                    'bonus_percent' => (float)($bonuses[$i] ?? 0),
                    'tier_type' => $types[$i] ?? 'Standard',
                    'sort_order' => $i,
                    'status' => 'active'
                ]);
            }
        }
        
        $message = 'Bonus tiers saved successfully!';
        $messageType = 'success';
    }
    
    // Upload QR Code
    if ($action === 'upload_qr') {
        if (!empty($_FILES['qr_image']['name'])) {
            $allowedTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/webp'];
            $fileType = $_FILES['qr_image']['type'];
            
            if (!in_array($fileType, $allowedTypes)) {
                $message = 'Invalid file type. Only PNG, JPG, WEBP allowed.';
                $messageType = 'error';
            } elseif ($_FILES['qr_image']['size'] > 2 * 1024 * 1024) {
                $message = 'File too large. Maximum 2MB allowed.';
                $messageType = 'error';
            } else {
                $uploadDir = ROOT_PATH . '/assets/images/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                
                $filename = 'payment-qr.png';
                if (move_uploaded_file($_FILES['qr_image']['tmp_name'], $uploadDir . $filename)) {
                    $message = 'QR Code uploaded successfully!';
                    $messageType = 'success';
                } else {
                    $message = 'Failed to upload QR Code.';
                    $messageType = 'error';
                }
            }
        } else {
            $message = 'Please select a QR Code image.';
            $messageType = 'error';
        }
    }
}

// Get current settings
$upiSettings = [
    'upi_merchant_name' => getSetting('upi_merchant_name', 'Merchant Name'),
    'upi_id' => getSetting('upi_id', 'merchant@upi'),
    'upi_min_deposit' => getSetting('upi_min_deposit', 100),
    'upi_max_deposit' => getSetting('upi_max_deposit', 100000),
    'upi_payment_timeout' => getSetting('upi_payment_timeout', 600),
    'upi_status' => getSetting('upi_status', 'active'),
];

$bonusSettings = [
    'deposit_bonus_enabled' => getSetting('deposit_bonus_enabled', '0'),
    'deposit_bonus_percent' => getSetting('deposit_bonus_percent', 0),
    'deposit_bonus_min_amount' => getSetting('deposit_bonus_min_amount', 0),
    'deposit_bonus_max_bonus' => getSetting('deposit_bonus_max_bonus', 0),
    'bonus_turnover_multiplier' => getSetting('bonus_turnover_multiplier', 30),
    'cfd_balance_multiplier' => getSetting('cfd_balance_multiplier', 3),
];

// Get bonus tiers
$bonusTiers = dbFetchAll("SELECT * FROM deposit_bonus_tiers ORDER BY sort_order ASC");
if (empty($bonusTiers)) {
    // Default tiers
    $bonusTiers = [
        ['min_amount' => 40000, 'bonus_percent' => 50, 'tier_type' => 'Gold'],
        ['min_amount' => 7000, 'bonus_percent' => 20, 'tier_type' => 'Standard'],
        ['min_amount' => 3500, 'bonus_percent' => 10, 'tier_type' => 'Standard'],
        ['min_amount' => 700, 'bonus_percent' => 0, 'tier_type' => 'Standard'],
    ];
}

// Check if QR exists
$qrExists = file_exists(ROOT_PATH . '/assets/images/payment-qr.png');

// Stats
$stats = [
    'today_deposits' => dbFetch("SELECT COUNT(*) as c, COALESCE(SUM(amount), 0) as t FROM upi_payments WHERE status = 'completed' AND DATE(completed_at) = CURDATE()")
];
?>

<style>
.settings-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 1.5rem; }
.settings-card { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 16px; overflow: hidden; }
.settings-header { background: var(--bg-tertiary); padding: 1rem 1.5rem; border-bottom: 1px solid var(--border-color); display: flex; align-items: center; gap: 0.75rem; }
.settings-header i { font-size: 1.25rem; color: var(--accent-green); }
.settings-header h3 { margin: 0; font-size: 1rem; }
.settings-body { padding: 1.5rem; }
.qr-preview { text-align: center; margin-bottom: 1.5rem; }
.qr-preview img { max-width: 200px; border-radius: 12px; border: 2px solid var(--border-color); }
.qr-preview .no-qr { width: 200px; height: 200px; background: var(--bg-tertiary); border-radius: 12px; display: flex; align-items: center; justify-content: center; margin: 0 auto; color: var(--text-muted); flex-direction: column; gap: 0.5rem; }
.tier-row { display: flex; gap: 0.75rem; margin-bottom: 0.75rem; align-items: center; }
.tier-row input, .tier-row select { flex: 1; }
.tier-row .remove-tier { background: var(--accent-red); color: #fff; border: none; padding: 0.5rem; border-radius: 6px; cursor: pointer; }
.add-tier-btn { background: var(--bg-tertiary); border: 2px dashed var(--border-color); padding: 0.75rem; border-radius: 8px; width: 100%; cursor: pointer; color: var(--text-muted); transition: all 0.3s; }
.add-tier-btn:hover { border-color: var(--accent-green); color: var(--accent-green); }
.bonus-preview { background: var(--bg-tertiary); border-radius: 12px; padding: 1rem; margin-top: 1rem; }
.bonus-preview h5 { margin-bottom: 0.75rem; font-size: 0.85rem; color: var(--text-muted); }
.bonus-tier-preview { display: flex; gap: 0.5rem; flex-wrap: wrap; }
.tier-badge { background: var(--bg-card); border: 1px solid var(--border-color); padding: 0.5rem 1rem; border-radius: 8px; font-size: 0.85rem; }
.tier-badge.gold { border-color: #fbbf24; background: rgba(251,191,36,0.1); }
.tier-badge .amount { font-weight: 700; }
.tier-badge .percent { color: var(--accent-green); }
.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
.status-toggle { display: flex; align-items: center; gap: 1rem; padding: 1rem; background: var(--bg-tertiary); border-radius: 8px; }
.status-toggle .toggle-switch { position: relative; width: 50px; height: 26px; }
.status-toggle input { opacity: 0; width: 0; height: 0; }
.status-toggle .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background: #4b5563; border-radius: 26px; transition: 0.3s; }
.status-toggle .slider:before { position: absolute; content: ""; height: 20px; width: 20px; left: 3px; bottom: 3px; background: #fff; border-radius: 50%; transition: 0.3s; }
.status-toggle input:checked + .slider { background: var(--accent-green); }
.status-toggle input:checked + .slider:before { transform: translateX(24px); }
.upi-id-display { background: var(--bg-primary); padding: 1rem; border-radius: 8px; font-family: var(--font-mono); display: flex; align-items: center; justify-content: space-between; margin-top: 0.5rem; }
</style>

<div class="page-header">
    <h1 class="page-title"><i class="fas fa-qrcode"></i> UPI Payment Gateway Settings</h1>
</div>

<?php if ($message): ?>
<div class="alert alert-<?= $messageType === 'success' ? 'success' : 'danger' ?> mb-4"><?= $message ?></div>
<?php endif; ?>

<!-- Quick Stats -->
<div class="row mb-4">
    <div class="col-md-4 mb-3">
        <div class="stat-card">
            <div class="stat-icon" style="background: rgba(0,208,156,0.2); color: #00d09c;"><i class="fas fa-check-circle"></i></div>
            <div class="stat-value"><?= $stats['today_deposits']['c'] ?? 0 ?></div>
            <div class="stat-label">Today's Deposits</div>
        </div>
    </div>
    <div class="col-md-4 mb-3">
        <div class="stat-card">
            <div class="stat-icon" style="background: rgba(99,102,241,0.2); color: #6366f1;"><i class="fas fa-rupee-sign"></i></div>
            <div class="stat-value">₹<?= number_format($stats['today_deposits']['t'] ?? 0) ?></div>
            <div class="stat-label">Today's Volume</div>
        </div>
    </div>
    <div class="col-md-4 mb-3">
        <div class="stat-card">
            <div class="stat-icon" style="background: rgba(251,191,36,0.2); color: #fbbf24;"><i class="fas fa-gift"></i></div>
            <div class="stat-value"><?= $bonusSettings['deposit_bonus_percent'] ?>%</div>
            <div class="stat-label">Current Bonus</div>
        </div>
    </div>
</div>

<div class="settings-grid">
    <!-- QR Code Upload -->
    <div class="settings-card">
        <div class="settings-header">
            <i class="fas fa-qrcode"></i>
            <h3>QR Code</h3>
        </div>
        <div class="settings-body">
            <div class="qr-preview">
                <?php if ($qrExists): ?>
                <img src="<?= SITE_URL ?>/assets/images/payment-qr.png?v=<?= time() ?>" alt="Payment QR">
                <?php else: ?>
                <div class="no-qr">
                    <i class="fas fa-qrcode fa-3x"></i>
                    <span>No QR Uploaded</span>
                </div>
                <?php endif; ?>
            </div>
            
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="upload_qr">
                <div class="form-group mb-3">
                    <label class="form-label">Upload New QR Code</label>
                    <input type="file" name="qr_image" class="form-control" accept="image/png,image/jpeg,image/webp">
                    <small class="text-muted">PNG, JPG, WEBP. Max 2MB.</small>
                </div>
                <button type="submit" class="btn btn-primary btn-block">
                    <i class="fas fa-upload"></i> Upload QR Code
                </button>
            </form>
        </div>
    </div>
    
    <!-- UPI Settings -->
    <div class="settings-card">
        <div class="settings-header">
            <i class="fas fa-mobile-alt"></i>
            <h3>UPI Settings</h3>
        </div>
        <div class="settings-body">
            <form method="POST">
                <input type="hidden" name="action" value="save_upi_settings">
                
                <div class="form-group mb-3">
                    <label class="form-label">Merchant Name</label>
                    <input type="text" name="upi_merchant_name" class="form-control" value="<?= htmlspecialchars($upiSettings['upi_merchant_name']) ?>" required>
                </div>
                
                <div class="form-group mb-3">
                    <label class="form-label">UPI ID</label>
                    <input type="text" name="upi_id" class="form-control" value="<?= htmlspecialchars($upiSettings['upi_id']) ?>" required placeholder="yourname@upi">
                    <div class="upi-id-display">
                        <span><?= htmlspecialchars($upiSettings['upi_id']) ?></span>
                        <i class="fas fa-bolt" style="color: #f7931a;"></i>
                    </div>
                </div>
                
                <div class="form-row mb-3">
                    <div class="form-group">
                        <label class="form-label">Minimum Deposit (₹)</label>
                        <input type="number" name="upi_min_deposit" class="form-control" value="<?= $upiSettings['upi_min_deposit'] ?>" min="1">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Maximum Deposit (₹)</label>
                        <input type="number" name="upi_max_deposit" class="form-control" value="<?= $upiSettings['upi_max_deposit'] ?>" min="1">
                    </div>
                </div>
                
                <div class="form-group mb-3">
                    <label class="form-label">Payment Timeout (seconds)</label>
                    <input type="number" name="upi_payment_timeout" class="form-control" value="<?= $upiSettings['upi_payment_timeout'] ?>" min="60">
                    <small class="text-muted">Default: 600 (10 minutes)</small>
                </div>
                
                <div class="status-toggle mb-3">
                    <label class="toggle-switch">
                        <input type="checkbox" name="upi_status" value="active" <?= $upiSettings['upi_status'] === 'active' ? 'checked' : '' ?>>
                        <span class="slider"></span>
                    </label>
                    <div>
                        <strong>UPI Payments</strong>
                        <div class="text-muted" style="font-size:0.8rem;">Enable/disable UPI deposit option</div>
                    </div>
                </div>
                
                <button type="submit" class="btn btn-primary btn-block">
                    <i class="fas fa-save"></i> Save UPI Settings
                </button>
            </form>
        </div>
    </div>
    
    <!-- Bonus Settings -->
    <div class="settings-card">
        <div class="settings-header">
            <i class="fas fa-gift"></i>
            <h3>Deposit Bonus Settings</h3>
        </div>
        <div class="settings-body">
            <form method="POST">
                <input type="hidden" name="action" value="save_bonus_settings">
                
                <div class="status-toggle mb-3">
                    <label class="toggle-switch">
                        <input type="checkbox" name="deposit_bonus_enabled" value="1" <?= $bonusSettings['deposit_bonus_enabled'] === '1' ? 'checked' : '' ?>>
                        <span class="slider"></span>
                    </label>
                    <div>
                        <strong>Enable Deposit Bonus</strong>
                        <div class="text-muted" style="font-size:0.8rem;">Give bonus on deposits</div>
                    </div>
                </div>
                
                <div class="form-row mb-3">
                    <div class="form-group">
                        <label class="form-label">Default Bonus (%)</label>
                        <input type="number" name="deposit_bonus_percent" class="form-control" value="<?= $bonusSettings['deposit_bonus_percent'] ?>" min="0" max="100" step="0.1">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Minimum Deposit for Bonus (₹)</label>
                        <input type="number" name="deposit_bonus_min_amount" class="form-control" value="<?= $bonusSettings['deposit_bonus_min_amount'] ?>" min="0">
                    </div>
                </div>
                
                <div class="form-group mb-3">
                    <label class="form-label">Maximum Bonus Amount (₹)</label>
                    <input type="number" name="deposit_bonus_max_bonus" class="form-control" value="<?= $bonusSettings['deposit_bonus_max_bonus'] ?>" min="0">
                    <small class="text-muted">0 = No limit</small>
                </div>
                
                <div class="form-row mb-3">
                    <div class="form-group">
                        <label class="form-label">Binary Turnover Multiplier (x)</label>
                        <input type="number" name="bonus_turnover_multiplier" class="form-control" value="<?= $bonusSettings['bonus_turnover_multiplier'] ?>" min="1" step="0.1">
                        <small class="text-muted">e.g., 30 = 3000% of (Deposit+Bonus)</small>
                    </div>
                    <div class="form-group">
                        <label class="form-label">CFD Balance Multiplier (x)</label>
                        <input type="number" name="cfd_balance_multiplier" class="form-control" value="<?= $bonusSettings['cfd_balance_multiplier'] ?>" min="1" step="0.1">
                        <small class="text-muted">e.g., 3 = Balance ≥ 3× (Deposit+Bonus)</small>
                    </div>
                </div>
                
                <button type="submit" class="btn btn-primary btn-block">
                    <i class="fas fa-save"></i> Save Bonus Settings
                </button>
            </form>
        </div>
    </div>
    
    <!-- Bonus Tiers -->
    <div class="settings-card">
        <div class="settings-header">
            <i class="fas fa-layer-group"></i>
            <h3>Bonus Tiers (Binomo Style)</h3>
        </div>
        <div class="settings-body">
            <form method="POST" id="tiersForm">
                <input type="hidden" name="action" value="save_bonus_tiers">
                
                <div id="tiersContainer">
                    <?php foreach ($bonusTiers as $i => $tier): ?>
                    <div class="tier-row">
                        <input type="number" name="tier_amount[]" class="form-control" placeholder="Min Amount (₹)" value="<?= $tier['min_amount'] ?>">
                        <input type="number" name="tier_bonus[]" class="form-control" placeholder="Bonus %" value="<?= $tier['bonus_percent'] ?>" min="0" max="100">
                        <select name="tier_type[]" class="form-control">
                            <option value="Standard" <?= $tier['tier_type'] === 'Standard' ? 'selected' : '' ?>>Standard 🔷</option>
                            <option value="Gold" <?= $tier['tier_type'] === 'Gold' ? 'selected' : '' ?>>Gold 💎</option>
                            <option value="Platinum" <?= $tier['tier_type'] === 'Platinum' ? 'selected' : '' ?>>Platinum 👑</option>
                        </select>
                        <button type="button" class="remove-tier" onclick="removeTier(this)"><i class="fas fa-times"></i></button>
                    </div>
                    <?php endforeach; ?>
                </div>
                
                <button type="button" class="add-tier-btn mb-3" onclick="addTier()">
                    <i class="fas fa-plus"></i> Add Tier
                </button>
                
                <div class="bonus-preview">
                    <h5>Preview (as shown to users)</h5>
                    <div class="bonus-tier-preview" id="tierPreview">
                        <?php foreach ($bonusTiers as $tier): ?>
                        <div class="tier-badge <?= strtolower($tier['tier_type']) ?>">
                            <span class="amount">₹<?= number_format($tier['min_amount']) ?></span>
                            <span class="percent">+<?= $tier['bonus_percent'] ?>%</span>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                
                <button type="submit" class="btn btn-primary btn-block mt-3">
                    <i class="fas fa-save"></i> Save Bonus Tiers
                </button>
            </form>
        </div>
    </div>
</div>

<script>
function addTier() {
    const container = document.getElementById('tiersContainer');
    const row = document.createElement('div');
    row.className = 'tier-row';
    row.innerHTML = `
        <input type="number" name="tier_amount[]" class="form-control" placeholder="Min Amount (₹)">
        <input type="number" name="tier_bonus[]" class="form-control" placeholder="Bonus %" min="0" max="100">
        <select name="tier_type[]" class="form-control">
            <option value="Standard">Standard 🔷</option>
            <option value="Gold">Gold 💎</option>
            <option value="Platinum">Platinum 👑</option>
        </select>
        <button type="button" class="remove-tier" onclick="removeTier(this)"><i class="fas fa-times"></i></button>
    `;
    container.appendChild(row);
}

function removeTier(btn) {
    const rows = document.querySelectorAll('.tier-row');
    if (rows.length > 1) {
        btn.closest('.tier-row').remove();
    } else {
        alert('At least one tier is required');
    }
}
</script>

<?php require_once 'includes/footer.php'; ?>
