<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

if (!isset($_SESSION['admin_logged_in']) || !isset($_SESSION['admin_user']) || !isset($_SESSION['admin_pass'])) {
    header("Location: admin_login.php");
    exit;
}

$config_loaded = false;
$config_paths = ['Config.php', 'config.php', '../Config.php', '../config.php'];
foreach ($config_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        $config_loaded = true;
        break;
    }
}

if (!$config_loaded) {
    die("<div style='background:#ff4d4d; color:#fff; padding:20px; text-align:center; border-radius:12px; margin:50px auto; max-width:600px;'><h2>Configuration File Missing!</h2></div>");
}

if (!isset($conn) && isset($con)) {
    $conn = $con;
}

$admin_user = $_SESSION['admin_user'];
$admin_pass = $_SESSION['admin_pass'];
$has_permission = false;

if (!$conn) {
    die("<div style='text-align:center; margin-top:50px;'><h2>Database Connection Failed!</h2><p>Please check config.php</p></div>");
}

$sql = "SELECT database_editing FROM modarator_permissions WHERE username = ? AND password = ?";
$perm_stmt = $conn->prepare($sql);

if ($perm_stmt === false) {
    die("<div style='text-align:center; margin-top:50px; color:red;'><h2>Database SQL Error!</h2><p>Error: " . $conn->error . "</p></div>");
}

$perm_stmt->bind_param("ss", $admin_user, $admin_pass);
$perm_stmt->execute();
$perm_result = $perm_stmt->get_result();

if ($row = $perm_result->fetch_assoc()) {
    if ($row['database_editing'] === 'Yes') {
        $has_permission = true;
    }
}
$perm_stmt->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>App Settings Manager</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root { --window-bg: rgba(255, 255, 255, 0.95); --text-main: #1e293b; --border-color: rgba(0, 0, 0, 0.1); }
        * { font-family: 'Inter', sans-serif; box-sizing: border-box; }
        body { background: linear-gradient(135deg, #0f2027 0%, #203a43 50%, #2c5364 100%); background-attachment: fixed; min-height: 100vh; padding: 2vh 1vw; color: var(--text-main); font-size: 13px; }
        .os-window { max-width: 1200px; margin: 0 auto; background: var(--window-bg); backdrop-filter: blur(25px); border-radius: 16px; box-shadow: 0 25px 50px -12px rgba(0,0,0,0.5); overflow: hidden; }
        .window-header { background: rgba(255, 255, 255, 0.7); padding: 15px 20px; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center; }
        .traffic-lights { display: flex; gap: 8px; }
        .dot { width: 12px; height: 12px; border-radius: 50%; }
        .dot.red { background: #ff5f56; } .dot.yellow { background: #ffbd2e; } .dot.green { background: #27c93f; }
        .window-content { padding: 30px; }
        .nav-pills { background: rgba(0,0,0,0.05); padding: 5px; border-radius: 10px; display: inline-flex; margin-bottom: 25px; }
        .nav-pills .nav-link { font-weight: 600; color: #64748b; border-radius: 8px; padding: 10px 25px; transition: 0.3s; cursor: pointer; }
        .nav-pills .nav-link.active { background: white; color: #0f2027; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); }
        .form-label { font-weight: 600; font-size: 12px; color: #475569; margin-bottom: 6px; text-transform: uppercase; letter-spacing: 0.5px;}
        .form-control, .form-select { font-size: 13px; border-radius: 8px; padding: 10px 15px; border: 1px solid #cbd5e1; background: #f8fafc; transition: 0.2s;}
        .form-control:focus, .form-select:focus { border-color: #3b82f6; background: #fff; box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); }
        .section-title { font-size: 15px; font-weight: 700; color: #0f2027; margin: 20px 0 15px; padding-bottom: 8px; border-bottom: 2px solid #e2e8f0; display: flex; align-items: center; gap: 8px;}
        .btn-save { background: linear-gradient(to right, #11998e, #38ef7d); color: white; border: none; padding: 12px 30px; border-radius: 8px; font-weight: 700; font-size: 14px; box-shadow: 0 4px 15px rgba(56, 239, 125, 0.4); transition: 0.3s; }
        .btn-save:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(56, 239, 125, 0.6); color: white;}
        .error-card { background: #fee2e2; border: 1px solid #ef4444; color: #991b1b; padding: 40px; border-radius: 12px; text-align: center; }
        .error-card i { font-size: 40px; color: #ef4444; margin-bottom: 15px; }
    </style>
</head>
<body>

<div class="toast-container position-fixed bottom-0 end-0 p-3" style="z-index: 1050;">
    <div id="liveToast" class="toast border-0 shadow" role="alert">
        <div class="toast-body fw-bold rounded" id="toastMsg" style="font-size: 14px; background: white;"></div>
    </div>
</div>

<div class="os-window">
    <div class="window-header">
        <div class="traffic-lights"><div class="dot red"></div><div class="dot yellow"></div><div class="dot green"></div></div>
        <div class="fw-bold text-secondary fs-6"><i class="fas fa-cogs"></i> Master App Settings</div>
        <a href="admin_login.php?logout=1" class="btn btn-sm btn-danger rounded-pill px-3 fw-bold"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>

    <div class="window-content">
        <?php if(!$has_permission): ?>
            <div class="error-card shadow-sm">
                <i class="fas fa-lock"></i>
                <h3>Access Denied!</h3>
                <p class="fs-6 mt-2">You do not have permission to view or edit database settings. Please contact the main administrator.</p>
            </div>
        <?php else: ?>
            <ul class="nav nav-pills" id="settingsTabs">
                <li class="nav-item"><a class="nav-link active" data-bs-toggle="pill" href="#tab_type1"><i class="fas fa-wallet"></i> Type 1 (Financial & Links)</a></li>
                <li class="nav-item"><a class="nav-link" data-bs-toggle="pill" href="#tab_type2"><i class="fas fa-sliders-h"></i> Type 2 (Controls & Notices)</a></li>
            </ul>

            <div class="tab-content">
                <div class="tab-pane fade show active" id="tab_type1">
                    <form id="form_Type1" onsubmit="saveData(event, 'Type1')">
                        <div class="section-title"><i class="fas fa-mobile-alt text-primary"></i> Payment Numbers</div>
                        <div class="row">
                            <div class="col-md-4 mb-3"><label class="form-label">bKash Number</label><input type="text" name="bkash_number" id="bkash_number" class="form-control"></div>
                            <div class="col-md-4 mb-3"><label class="form-label">Nagad Number</label><input type="text" name="nagad_number" id="nagad_number" class="form-control"></div>
                            <div class="col-md-4 mb-3"><label class="form-label">Rocket Number</label><input type="text" name="rocket_number" id="rocket_number" class="form-control"></div>
                        </div>

                        <div class="section-title"><i class="fas fa-chart-line text-success"></i> Financial Limits</div>
                        <div class="row">
                            <div class="col-md-3 mb-3"><label class="form-label">Min Deposit</label><input type="number" name="min_deposit" id="min_deposit" class="form-control"></div>
                            <div class="col-md-3 mb-3"><label class="form-label">Max Deposit</label><input type="number" name="maximumdp" id="maximumdp" class="form-control"></div>
                            <div class="col-md-3 mb-3"><label class="form-label">Min Withdraw</label><input type="number" name="min_withdraw" id="min_withdraw" class="form-control"></div>
                            <div class="col-md-3 mb-3"><label class="form-label">Max Withdraw</label><input type="number" name="maximumwd" id="maximumwd" class="form-control"></div>
                            <div class="col-md-4 mb-3"><label class="form-label">Min First DP</label><input type="number" name="min_firstdp" id="min_firstdp" class="form-control"></div>
                            <div class="col-md-4 mb-3"><label class="form-label">Referral Bonus</label><input type="number" name="referral_bonus" id="referral_bonus" class="form-control"></div>
                            <div class="col-md-4 mb-3"><label class="form-label">Daily Limit</label><input type="number" name="daily_limit" id="daily_limit" class="form-control"></div>
                        </div>

                        <div class="section-title"><i class="fas fa-link text-warning"></i> External Links</div>
                        <div class="row">
                            <div class="col-md-4 mb-3"><label class="form-label">Add Money Link</label><input type="text" name="add_money_link" id="add_money_link" class="form-control"></div>
                            <div class="col-md-4 mb-3"><label class="form-label">Collect Room Link</label><input type="text" name="collect_room_link" id="collect_room_link" class="form-control"></div>
                            <div class="col-md-4 mb-3"><label class="form-label">Admin Support Link</label><input type="text" name="admin_support_link" id="admin_support_link" class="form-control"></div>
                            <div class="col-md-4 mb-3"><label class="form-label">Join Match Link</label><input type="text" name="join_match_link" id="join_match_link" class="form-control"></div>
                            <div class="col-md-4 mb-3"><label class="form-label">Diamond Selling Link</label><input type="text" name="diamond_selling_link" id="diamond_selling_link" class="form-control"></div>
                            <div class="col-md-4 mb-3"><label class="form-label">Win Photo Upload Link</label><input type="text" name="win_photo_upload_link" id="win_photo_upload_link" class="form-control"></div>
                        </div>

                        <div class="section-title"><i class="fas fa-key text-danger"></i> API & Security Keys</div>
                        <div class="row">
                            <div class="col-md-4 mb-3"><label class="form-label">Secret Key</label><input type="text" name="secretkey" id="secretkey" class="form-control"></div>
                            <div class="col-md-4 mb-3"><label class="form-label">Brand Key</label><input type="text" name="brandkey" id="brandkey" class="form-control"></div>
                            <div class="col-md-4 mb-3"><label class="form-label">API Key</label><input type="text" name="apikey" id="apikey_1" class="form-control"></div>
                        </div>

                        <div class="text-end mt-3 border-top pt-3">
                            <button type="submit" class="btn-save"><i class="fas fa-save"></i> Save Type 1 Settings</button>
                        </div>
                    </form>
                </div>

                <div class="tab-pane fade" id="tab_type2">
                    <form id="form_Type2" onsubmit="saveData(event, 'Type2')">
                        <div class="section-title"><i class="fas fa-toggle-on text-primary"></i> Application Controls</div>
                        <div class="row">
                            <div class="col-md-3 mb-3"><label class="form-label">Application Status</label><select name="application_status" id="application_status" class="form-select"><option value="Open">Open</option><option value="Closed">Closed</option></select></div>
                            <div class="col-md-3 mb-3"><label class="form-label">Add Money</label><select name="addmoney_open" id="addmoney_open" class="form-select"><option value="Yes">Yes</option><option value="No">No</option></select></div>
                            <div class="col-md-3 mb-3"><label class="form-label">Withdraw</label><select name="withdraw_open" id="withdraw_open" class="form-select"><option value="Yes">Yes</option><option value="No">No</option></select></div>
                            <div class="col-md-3 mb-3"><label class="form-label">Auto Pay</label><select name="auto_pay" id="auto_pay" class="form-select"><option value="Yes">Yes</option><option value="No">No</option></select></div>
                            <div class="col-md-4 mb-3"><label class="form-label">Multiple Login</label><select name="multiple_login" id="multiple_login" class="form-select"><option value="Yes">Yes</option><option value="No">No</option></select></div>
                            <div class="col-md-4 mb-3"><label class="form-label">Withdraw Block Time</label><input type="text" name="withdraw_block_time" id="withdraw_block_time" class="form-control"></div>
                            <div class="col-md-4 mb-3"><label class="form-label">API Key</label><input type="text" name="api_key" id="api_key_2" class="form-control"></div>
                        </div>

                        <div class="section-title"><i class="fas fa-bullhorn text-warning"></i> Notices & Updates</div>
                        <div class="row">
                            <div class="col-md-6 mb-3"><label class="form-label">Home Notice</label><textarea name="home_notice" id="home_notice" class="form-control" rows="3"></textarea></div>
                            <div class="col-md-6 mb-3"><label class="form-label">Closed Reason</label><textarea name="closed_reason" id="closed_reason" class="form-control" rows="3"></textarea></div>
                            <div class="col-md-4 mb-3"><label class="form-label">Version Code</label><input type="number" name="version_code" id="version_code" class="form-control"></div>
                            <div class="col-md-4 mb-3"><label class="form-label">Update Link</label><input type="text" name="update_link" id="update_link" class="form-control"></div>
                            <div class="col-md-4 mb-3"><label class="form-label">Updated On</label><input type="date" name="updated_on" id="updated_on" class="form-control"></div>
                            <div class="col-12 mb-3"><label class="form-label">Update Notice</label><textarea name="update_notice" id="update_notice" class="form-control" rows="2"></textarea></div>
                        </div>

                        <div class="text-end mt-3 border-top pt-3">
                            <button type="submit" class="btn-save"><i class="fas fa-save"></i> Save Type 2 Settings</button>
                        </div>
                    </form>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

<?php if($has_permission): ?>
<script>
    const API_URL = "SettingPost.php";

    function showToast(msg, type) {
        let color = type === 'success' ? '#15803d' : '#b91c1c';
        let icon = type === 'success' ? '✅' : '❌';
        $('#toastMsg').html(`${icon} ${msg}`).css('color', color);
        new bootstrap.Toast(document.getElementById('liveToast'), { delay: 3000 }).show();
    }

    function fetchCurrentData() {
        $.get(API_URL, function(res) {
            if (res && res.status === 'success' && res.data) {
                const d = res.data;
                $('#bkash_number').val(d.bkash_number); $('#nagad_number').val(d.nagad_number); $('#rocket_number').val(d.rocket_number);
                $('#add_money_link').val(d.add_money_link); $('#collect_room_link').val(d.collect_room_link); $('#admin_support_link').val(d.admin_support_link);
                $('#join_match_link').val(d.join_match_link); $('#diamond_selling_link').val(d.diamond_selling_link); $('#win_photo_upload_link').val(d.win_photo_upload_link);
                $('#min_deposit').val(d.min_deposit); $('#min_withdraw').val(d.min_withdraw); $('#maximumdp').val(d.maximumdp);
                $('#maximumwd').val(d.maximumwd); $('#min_firstdp').val(d.min_firstdp); $('#referral_bonus').val(d.referral_bonus);
                $('#daily_limit').val(d.daily_limit); $('#secretkey').val(d.secretkey); $('#brandkey').val(d.brandkey); $('#apikey_1').val(d.apikey);
                
                $('#application_status').val(d.application_status); $('#addmoney_open').val(d.addmoney_open); $('#withdraw_open').val(d.withdraw_open);
                $('#auto_pay').val(d.auto_pay); $('#multiple_login').val(d.multiple_login); $('#withdraw_block_time').val(d.withdraw_block_time);
                $('#api_key_2').val(d.api_key); $('#home_notice').val(d.home_notice); $('#closed_reason').val(d.closed_reason);
                $('#version_code').val(d.version_code); $('#update_link').val(d.update_link); $('#updated_on').val(d.updated_on);
                $('#update_notice').val(d.update_notice);
            }
        }).fail(function() {
            showToast("Failed to fetch settings.", "error");
        });
    }

    function saveData(e, type) {
        e.preventDefault();
        let formData = $('#form_' + type).serialize() + `&type=${type}`;
        let btn = $(e.target).find('.btn-save');
        let orgText = btn.html();
        btn.html('<i class="fas fa-spinner fa-spin"></i> Saving...').prop('disabled', true);

        $.post(API_URL, formData, function(res) {
            btn.html(orgText).prop('disabled', false);
            if (res.status === 'success') {
                showToast(res.message, 'success');
            } else {
                showToast(res.message || "Permission Denied or Error", 'error');
            }
        }, 'json').fail(function() {
            btn.html(orgText).prop('disabled', false);
            showToast("Server Error or Access Denied!", "error");
        });
    }

    $(function() { fetchCurrentData(); });
</script>
<?php endif; ?>
</body>
</html>
