<?php
// TEMP DEBUG: force real errors to show instead of a blank page.
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start output buffering to prevent premature output
ob_start();

include "header.php";
include "config.php"; // Assuming config.php contains the database connection

// Initialize message variable
$message = "";

// Fetch existing settings from the database
$query = "SELECT * FROM site_settings LIMIT 1";
$result = mysqli_query($conn, $query);
$settings = mysqli_fetch_assoc($result);

// Toggle a cron job on/off (separate mini-form, handled before the main
// settings form below so it doesn't get mixed up with brand_name etc.)
if (isset($_POST['toggleCron']) && isset($_POST['job_key'])) {
    $jobKeyEsc = mysqli_real_escape_string($conn, $_POST['job_key']);
    $newState = ($_POST['toggleCron'] === 'enable') ? 1 : 0;
    mysqli_query($conn, "UPDATE cron_jobs SET is_enabled = $newState WHERE job_key = '$jobKeyEsc'");
    header("Location: sitesetting#cron-jobs");
    exit;
}

// Send Test Email (separate mini-form, uses whatever SMTP settings are
// currently saved in the DB - save the form first before testing).
$testEmailMessage = '';
if (isset($_POST['sendTestEmail'])) {
    include_once "../includes/notify_lib.php";
    $testTo = trim($_POST['test_email_to'] ?? '');
    if ($testTo === '') {
        $testEmailMessage = ['type' => 'error', 'text' => 'Email address daalein.'];
    } else {
        $brand = get_brand_name($conn);
        $html = render_email_template($brand, 'Test Email', '<p>Yeh ek test email hai — agar aap ise dekh pa rahe hain, to aapki SMTP settings sahi se kaam kar rahi hain! ✅</p>');
        $sent = send_smtp_email($conn, $testTo, 'Test', "Test Email from {$brand}", $html);
        $testEmailMessage = $sent
            ? ['type' => 'success', 'text' => 'Test email safaltapoorvak bhej diya gaya! Inbox (aur spam folder bhi) check karein.']
            : ['type' => 'error', 'text' => 'Bhejne me error: ' . smtp_last_error()];
    }
}

// Commission Settings mini-form (Admin only - see the role check near the
// top of the main form section below; this file already gates the whole
// page to Admin).
$commissionMessage = '';
if (isset($_POST['saveCommission'])) {
    $commType = ($_POST['commission_type'] ?? 'percent') === 'fixed' ? 'fixed' : 'percent';
    $commValue = (float)($_POST['commission_value'] ?? 0);
    if ($commValue < 0) { $commValue = 0; }

    $topupMin = (float)($_POST['wallet_topup_min'] ?? 10);
    $topupMax = (float)($_POST['wallet_topup_max'] ?? 50000);
    if ($topupMin < 1) { $topupMin = 1; }
    if ($topupMax < $topupMin) { $topupMax = $topupMin; }

    $stmt = $conn->prepare("UPDATE site_settings SET commission_type = ?, commission_value = ?, wallet_topup_min = ?, wallet_topup_max = ? WHERE id = ?");
    if (!$stmt) {
        // Most likely cause: wallet_topup_min/wallet_topup_max columns
        // don't exist yet - the wallet_migration_fix.sql ALTER TABLE
        // statements for them haven't been run on this DB. Fail softly
        // instead of a fatal error that blanks the whole page.
        $commissionMessage = ['type' => 'error', 'text' => 'Could not save - your database is missing the wallet_topup_min/wallet_topup_max columns. Run wallet_migration_fix.sql (the two ALTER TABLE `site_settings` lines) in phpMyAdmin, then try again.'];
    } else {
        $stmt->bind_param("sdddi", $commType, $commValue, $topupMin, $topupMax, $settings['id']);
        $stmt->execute();
        $stmt->close();

        $settings['commission_type'] = $commType;
        $settings['commission_value'] = $commValue;
        $settings['wallet_topup_min'] = $topupMin;
        $settings['wallet_topup_max'] = $topupMax;
        $commissionMessage = ['type' => 'success', 'text' => 'Commission & wallet settings updated.'];
    }
}

// Handle form submission (only the main settings form - not the cron
// toggle or test-email mini-forms, which are handled above and already
// exit/skip past this point on their own).
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['brand_name'])) {
    $brand_name = $_POST['brand_name'];
    $logo_url = $_POST['logo_url'];
    $site_link = $_POST['site_link'];
    $whatsapp_number = $_POST['whatsapp_number'];
    $copyright_text = $_POST['copyright_text'];
    $google_client_id = trim($_POST['google_client_id'] ?? '');
    $google_client_secret = trim($_POST['google_client_secret'] ?? '');
    $google_redirect_uri = trim($_POST['google_redirect_uri'] ?? '');
    $smtp_host = trim($_POST['smtp_host'] ?? '');
    $smtp_port = (int)($_POST['smtp_port'] ?? 587);
    $smtp_username = trim($_POST['smtp_username'] ?? '');
    $smtp_password_input = trim($_POST['smtp_password'] ?? '');
    // Blank means "leave unchanged" so the admin doesn't have to retype it every save.
    $smtp_password = ($smtp_password_input !== '') ? $smtp_password_input : ($settings['smtp_password'] ?? '');
    $smtp_encryption = in_array($_POST['smtp_encryption'] ?? 'tls', ['tls', 'ssl', 'none']) ? $_POST['smtp_encryption'] : 'tls';
    $smtp_from_email = trim($_POST['smtp_from_email'] ?? '');
    $smtp_from_name = trim($_POST['smtp_from_name'] ?? '');
    $register_otp_enabled = isset($_POST['register_otp_enabled']) ? 1 : 0;
    $login_otp_enabled = isset($_POST['login_otp_enabled']) ? 1 : 0;
    $cpanel_host = trim($_POST['cpanel_host'] ?? '');
    $cpanel_port = (int)($_POST['cpanel_port'] ?? 2083);
    $cpanel_username = trim($_POST['cpanel_username'] ?? '');
    $cpanel_api_token_input = trim($_POST['cpanel_api_token'] ?? '');
    $cpanel_api_token = ($cpanel_api_token_input !== '') ? $cpanel_api_token_input : ($settings['cpanel_api_token'] ?? '');
    $cpanel_docroot = trim($_POST['cpanel_docroot'] ?? '');

    if ($settings) {
        // Update existing record
        $update_query = "UPDATE site_settings SET brand_name='$brand_name', logo_url='$logo_url', site_link='$site_link', whatsapp_number='$whatsapp_number', copyright_text='$copyright_text', google_client_id='$google_client_id', google_client_secret='$google_client_secret', google_redirect_uri='$google_redirect_uri', smtp_host='$smtp_host', smtp_port=$smtp_port, smtp_username='$smtp_username', smtp_password='$smtp_password', smtp_encryption='$smtp_encryption', smtp_from_email='$smtp_from_email', smtp_from_name='$smtp_from_name', register_otp_enabled=$register_otp_enabled, login_otp_enabled=$login_otp_enabled, cpanel_host='$cpanel_host', cpanel_port=$cpanel_port, cpanel_username='$cpanel_username', cpanel_api_token='$cpanel_api_token', cpanel_docroot='$cpanel_docroot' WHERE id=".$settings['id'];
        if (mysqli_query($conn, $update_query)) {
            $message = "Settings updated successfully.";
        } else {
            $message = "Error updating settings: " . mysqli_error($conn);
        }
    } else {
        // Insert new record
        $insert_query = "INSERT INTO site_settings (brand_name, logo_url, site_link, whatsapp_number, copyright_text, google_client_id, google_client_secret, google_redirect_uri, smtp_host, smtp_port, smtp_username, smtp_password, smtp_encryption, smtp_from_email, smtp_from_name, register_otp_enabled, login_otp_enabled, cpanel_host, cpanel_port, cpanel_username, cpanel_api_token, cpanel_docroot) VALUES ('$brand_name', '$logo_url', '$site_link', '$whatsapp_number', '$copyright_text', '$google_client_id', '$google_client_secret', '$google_redirect_uri', '$smtp_host', $smtp_port, '$smtp_username', '$smtp_password', '$smtp_encryption', '$smtp_from_email', '$smtp_from_name', $register_otp_enabled, $login_otp_enabled, '$cpanel_host', $cpanel_port, '$cpanel_username', '$cpanel_api_token', '$cpanel_docroot')";
        if (mysqli_query($conn, $insert_query)) {
            $message = "Settings saved successfully.";
        } else {
            $message = "Error saving settings: " . mysqli_error($conn);
        }
    }

    // Redirect after form submission
    header("Location: sitesetting.php?message=" . urlencode($message));
    exit();
}

if($userdata["role"] != 'Admin'){
   echo '<script>
 window.location.href = "dashboard";
</script>';

    exit;
}


// End output buffering and flush output
ob_end_flush();
?>
<?php if($userdata["role"] == 'Admin'){  ?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">

<style>
    :root{
        --p:#6c63ff; --p2:#e040fb;
        --g: linear-gradient(135deg,#6c63ff,#e040fb);
    }
    *{box-sizing:border-box}
    html, body, .content-wrapper{ background:#0a0a12 !important; }
    body{ font-family:'Inter',sans-serif; color:#fff; }
    .content-wrapper{min-height:100vh}

    .site-wrap{padding:20px;max-width:700px;margin:0 auto;animation:pageIn .4s ease both}
    @keyframes pageIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}

    .site-head{margin-bottom:22px}
    .site-head h1{font-size:1.5rem;font-weight:800;margin:0;color:#fff;display:flex;align-items:center;gap:10px}
    .site-head h1 .icn{
        width:38px;height:38px;border-radius:12px;background:var(--g);display:inline-flex;
        align-items:center;justify-content:center;font-size:16px;box-shadow:0 6px 18px rgba(108,99,255,.35);
    }
    .site-head p{font-size:.85rem;color:rgba(255,255,255,.45);margin:4px 0 0 48px}

    .glass-card{
        background:rgba(255,255,255,.04);backdrop-filter:blur(20px);
        border:1px solid rgba(255,255,255,.08);border-radius:20px;overflow:hidden;
    }
    .card-body{padding:26px}

    .form-group{margin-bottom:18px}
    .form-label{display:block;font-size:.78rem;font-weight:600;color:rgba(255,255,255,.5);margin-bottom:7px;text-transform:uppercase;letter-spacing:.3px}
    .form-control{
        width:100%;background:rgba(255,255,255,.05);border:1.5px solid rgba(255,255,255,.1);border-radius:10px;
        padding:12px 14px;color:#fff;font-size:.9rem;outline:none;transition:.2s;font-family:'Inter',sans-serif;
    }
    .form-control:focus{border-color:var(--p);background:rgba(108,99,255,.08);box-shadow:0 0 0 3px rgba(108,99,255,.15)}
    .form-control::placeholder{color:rgba(255,255,255,.3)}

    .logo-row{display:flex;gap:14px;align-items:center}
    .logo-preview{
        width:52px;height:52px;border-radius:12px;background:rgba(255,255,255,.05);border:1.5px solid rgba(255,255,255,.1);
        display:flex;align-items:center;justify-content:center;overflow:hidden;flex-shrink:0;
    }
    .logo-preview img{width:100%;height:100%;object-fit:contain}
    .logo-preview i{color:rgba(255,255,255,.2);font-size:1.2rem}

    .btn-primary-cta{
        width:100%;background:var(--g);border:none;color:#fff;padding:13px;border-radius:10px;
        font-size:.9rem;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;
        transition:.2s;box-shadow:0 6px 18px rgba(108,99,255,.3);margin-top:8px;
    }
    .btn-primary-cta:hover{transform:translateY(-1px);box-shadow:0 10px 24px rgba(108,99,255,.45);color:#fff}
</style>

<div class="site-wrap">
    <div class="site-head">
        <h1><span class="icn"><i class="fas fa-gear"></i></span>Site Settings</h1>
        <p>Brand identity shown across your platform and payment pages</p>
    </div>

    <div class="glass-card">
        <div class="card-body">
            <form method="post" action="sitesetting.php" id="siteSettingsForm">
                <div class="form-group">
                    <label class="form-label">Brand Name</label>
                    <input class="form-control" type="text" name="brand_name" placeholder="Eg. NeoPay" value="<?php echo htmlspecialchars($settings['brand_name'] ?? ''); ?>">
                </div>

                <div class="form-group">
                    <label class="form-label">Logo URL</label>
                    <div class="logo-row">
                        <div class="logo-preview" id="logoPreview"><i class="fas fa-image"></i></div>
                        <input class="form-control" type="text" name="logo_url" id="logoUrlInput" placeholder="https://example.com/logo.png" value="<?php echo htmlspecialchars($settings['logo_url'] ?? ''); ?>">
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Site Link</label>
                    <input class="form-control" type="text" name="site_link" placeholder="https://yoursite.com" value="<?php echo htmlspecialchars($settings['site_link'] ?? ''); ?>">
                </div>

                <div class="form-group">
                    <label class="form-label">WhatsApp Number</label>
                    <input class="form-control" type="text" name="whatsapp_number" placeholder="91XXXXXXXXXX" value="<?php echo htmlspecialchars($settings['whatsapp_number'] ?? ''); ?>">
                </div>

                <div class="form-group">
                    <label class="form-label">Copyright Text</label>
                    <input class="form-control" type="text" name="copyright_text" placeholder="© 2026 Your Company" value="<?php echo htmlspecialchars($settings['copyright_text'] ?? ''); ?>">
                </div>

                <div class="form-group" style="border-top:1px solid rgba(255,255,255,.08);margin-top:24px;padding-top:20px">
                    <label class="form-label" style="color:#fff;font-size:.9rem;margin-bottom:14px"><i class="fab fa-google" style="color:#e040fb"></i>&nbsp; Google Login (FamPay Connect)</label>
                    <p style="font-size:.78rem;color:rgba(255,255,255,.4);margin:-6px 0 14px">Neeche steps follow karke Google se Client ID/Secret le aayein, phir dono values + Redirect URI yahan save karein.</p>
                </div>

                <?php
                    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
                    $host = $_SERVER['HTTP_HOST'] ?? 'yoursite.com';
                    $suggestedRedirect = $scheme . '://' . $host . '/auth/fampay_oauth_callback';
                ?>
                <div class="oauth-guide">
                    <div class="oauth-guide-title"><i class="fas fa-list-ol"></i> Kaise setup karein (ek baar ka kaam)</div>
                    <ol>
                        <li>
                            Browser me <a href="https://console.cloud.google.com/" target="_blank" rel="noopener">console.cloud.google.com</a> kholein aur Google account se login karein.
                        </li>
                        <li>
                            Top-left me <b>"Select a project"</b> &gt; <b>"New Project"</b>. Koi bhi naam de dein (e.g. "<?php echo htmlspecialchars($settings['brand_name'] ?? 'NeoPay'); ?>") &gt; Create.
                        </li>
                        <li>
                            Left menu me <b>APIs &amp; Services &gt; Library</b> me jaake <b>"Gmail API"</b> search karein aur <b>Enable</b> karein. <span class="warn">(Yeh miss mat karna — isके bina FamPay payment verify kabhi kaam nahi karega.)</span>
                        </li>
                        <li>
                            <b>APIs &amp; Services &gt; OAuth consent screen</b> pe jaakar:
                            <ul>
                                <li>User Type: <b>External</b> chunein &gt; Create.</li>
                                <li>App name, support email, developer email bhar dein &gt; Save and Continue.</li>
                                <li><b>Scopes</b> step me "Add or Remove Scopes" &gt; Gmail API ka <code>.../auth/gmail.readonly</code> select karein &gt; Save and Continue.</li>
                                <li><b>Test users</b> step me apne aur apne merchants ke Gmail address add karein (jab tak app "Testing" mode me hai, sirf yahan add kiye hue accounts hi login kar payenge).</li>
                            </ul>
                        </li>
                        <li>
                            <b>APIs &amp; Services &gt; Credentials &gt; + Create Credentials &gt; OAuth client ID</b>.
                            <ul>
                                <li>Application type: <b>Web application</b>.</li>
                                <li><b>Authorized redirect URIs</b> me neeche di gayi exact URL paste karein (yehi wahi URL hai jo "Google Redirect URI" field me bhi neeche daalni hai — dono jagah hoobahoo same honi chahiye):</li>
                            </ul>
                            <div class="copy-row">
                                <code id="redirectUriHint"><?php echo htmlspecialchars($suggestedRedirect); ?></code>
                                <button type="button" class="copy-btn" onclick="copyRedirectUri()"><i class="fas fa-copy"></i> Copy</button>
                            </div>
                        </li>
                        <li>
                            Create dabate hi ek popup me <b>Client ID</b> aur <b>Client Secret</b> dikhega — dono copy karke neeche wale form me paste karein, aur upar wali Redirect URI bhi neeche ke field me paste karein &gt; Save Settings.
                        </li>
                    </ol>
                </div>
                <style>
                    .oauth-guide{background:rgba(224,64,251,.05);border:1px solid rgba(224,64,251,.18);border-radius:14px;padding:16px 18px;margin-bottom:20px}
                    .oauth-guide-title{font-size:.85rem;font-weight:700;color:#fff;margin-bottom:10px;display:flex;align-items:center;gap:8px}
                    .oauth-guide-title i{color:#e040fb}
                    .oauth-guide ol{margin:0;padding-left:20px;display:flex;flex-direction:column;gap:10px}
                    .oauth-guide li{font-size:.8rem;color:rgba(255,255,255,.65);line-height:1.55}
                    .oauth-guide li b{color:#fff}
                    .oauth-guide li ul{margin:6px 0 0;padding-left:18px;display:flex;flex-direction:column;gap:5px}
                    .oauth-guide code{background:rgba(255,255,255,.07);color:#43e97b;padding:2px 6px;border-radius:5px;font-size:.75rem}
                    .oauth-guide .warn{color:#f5b93b}
                    .copy-row{display:flex;align-items:center;gap:8px;margin-top:8px;background:rgba(0,0,0,.25);border:1px solid rgba(255,255,255,.08);border-radius:8px;padding:8px 10px;flex-wrap:wrap}
                    .copy-row code{background:none;padding:0;word-break:break-all;flex:1}
                    .copy-btn{background:var(--g);border:none;color:#fff;font-size:.72rem;font-weight:700;padding:6px 12px;border-radius:7px;cursor:pointer;white-space:nowrap}
                </style>

                <div class="form-group">
                    <label class="form-label">Google Client ID</label>
                    <input class="form-control" type="text" name="google_client_id" placeholder="xxxxxx.apps.googleusercontent.com" value="<?php echo htmlspecialchars($settings['google_client_id'] ?? ''); ?>">
                    <div class="field-hint">Credentials page pe "OAuth 2.0 Client IDs" ke niche jo ID dikhta hai, wahi yahan paste karein.</div>
                </div>
                <div class="form-group">
                    <label class="form-label">Google Client Secret</label>
                    <input class="form-control" type="text" name="google_client_secret" placeholder="Client Secret" value="<?php echo htmlspecialchars($settings['google_client_secret'] ?? ''); ?>">
                    <div class="field-hint">Client ID ke saath hi Google popup me "Client secret" bhi dikhta hai — usse copy karke yahan daalein.</div>
                </div>
                <div class="form-group">
                    <label class="form-label">Google Redirect URI</label>
                    <input class="form-control" type="text" name="google_redirect_uri" id="googleRedirectUriInput" placeholder="https://yoursite.com/auth/fampay_oauth_callback" value="<?php echo htmlspecialchars($settings['google_redirect_uri'] ?? $suggestedRedirect); ?>">
                    <div class="field-hint">Yahan wahi URL daalein jo Step 5 me Google Console ke "Authorized redirect URIs" me daali thi — aapki site ke liye woh hai: <code><?php echo htmlspecialchars($suggestedRedirect); ?></code></div>
                </div>
                <style>.field-hint{font-size:.72rem;color:rgba(255,255,255,.4);margin-top:6px;line-height:1.4}.field-hint code{background:rgba(255,255,255,.07);color:#43e97b;padding:1px 5px;border-radius:4px}</style>

                <hr style="border-color:rgba(255,255,255,.08);margin:28px 0">
                <h3 style="font-size:1rem;margin:0 0 4px"><i class="fas fa-envelope"></i> Email (SMTP)</h3>
                <p class="field-hint" style="margin-bottom:16px">Registration OTP, login OTP, security alerts, aur subscription reminders yahi se bhejte hain. Gmail use kar rahe hain to "App Password" banayein (normal password kaam nahi karega).</p>

                <div class="form-group">
                    <label class="form-label">SMTP Host</label>
                    <input class="form-control" type="text" name="smtp_host" placeholder="smtp.gmail.com" value="<?php echo htmlspecialchars($settings['smtp_host'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label class="form-label">SMTP Port</label>
                    <input class="form-control" type="number" name="smtp_port" placeholder="587" value="<?php echo htmlspecialchars($settings['smtp_port'] ?? '587'); ?>">
                    <div class="field-hint">587 = TLS (most common), 465 = SSL, 25 = None.</div>
                </div>
                <div class="form-group">
                    <label class="form-label">Encryption</label>
                    <select class="form-control" name="smtp_encryption">
                        <?php $curEnc = $settings['smtp_encryption'] ?? 'tls'; ?>
                        <option value="tls" <?php echo $curEnc === 'tls' ? 'selected' : ''; ?>>TLS (STARTTLS)</option>
                        <option value="ssl" <?php echo $curEnc === 'ssl' ? 'selected' : ''; ?>>SSL</option>
                        <option value="none" <?php echo $curEnc === 'none' ? 'selected' : ''; ?>>None</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">SMTP Username</label>
                    <input class="form-control" type="text" name="smtp_username" placeholder="you@gmail.com" value="<?php echo htmlspecialchars($settings['smtp_username'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label class="form-label">SMTP Password</label>
                    <input class="form-control" type="password" name="smtp_password" placeholder="<?php echo !empty($settings['smtp_password']) ? '•••••••• (saved - blank rehne dein badalna na ho to)' : 'App Password'; ?>" value="">
                </div>
                <div class="form-group">
                    <label class="form-label">From Email</label>
                    <input class="form-control" type="text" name="smtp_from_email" placeholder="noreply@yoursite.com" value="<?php echo htmlspecialchars($settings['smtp_from_email'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label class="form-label">From Name</label>
                    <input class="form-control" type="text" name="smtp_from_name" placeholder="NeoPay" value="<?php echo htmlspecialchars($settings['smtp_from_name'] ?? ''); ?>">
                </div>
                <div class="form-group" style="display:flex;align-items:center;gap:10px">
                    <input type="checkbox" name="register_otp_enabled" id="registerOtpEnabled" value="1" <?php echo (($settings['register_otp_enabled'] ?? 1) == 1) ? 'checked' : ''; ?>>
                    <label for="registerOtpEnabled" style="margin:0">Registration ke time Email OTP verification zaroori ho</label>
                </div>
                <div class="form-group" style="display:flex;align-items:center;gap:10px">
                    <input type="checkbox" name="login_otp_enabled" id="loginOtpEnabled" value="1" <?php echo (($settings['login_otp_enabled'] ?? 1) == 1) ? 'checked' : ''; ?>>
                    <label for="loginOtpEnabled" style="margin:0">Har login pe Email OTP verification zaroori ho (2FA)</label>
                </div>

                <hr style="border-color:rgba(255,255,255,.08);margin:28px 0">
                <h3 style="font-size:1rem;margin:0 0 4px"><i class="fas fa-server"></i> cPanel API (Auto Addon Domain)</h3>
                <p class="field-hint" style="margin-bottom:16px">Isse merchants ka White-Label domain <b>automatically</b> cPanel me add ho jaayega (DNS verify hote hi) - koi manual Addon Domain step nahi karna padega. Token cPanel -> Security -> Manage API Tokens se banayein.</p>

                <div class="form-group">
                    <label class="form-label">cPanel Host</label>
                    <input class="form-control" type="text" name="cpanel_host" placeholder="dns.myperfectdns.com" value="<?php echo htmlspecialchars($settings['cpanel_host'] ?? ''); ?>">
                    <div class="field-hint">Bina <code>https://</code> aur bina trailing slash ke.</div>
                </div>
                <div class="form-group">
                    <label class="form-label">Port</label>
                    <input class="form-control" type="number" name="cpanel_port" placeholder="2083" value="<?php echo htmlspecialchars($settings['cpanel_port'] ?? '2083'); ?>">
                </div>
                <div class="form-group">
                    <label class="form-label">cPanel Username</label>
                    <input class="form-control" type="text" name="cpanel_username" placeholder="viphostpro" value="<?php echo htmlspecialchars($settings['cpanel_username'] ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label class="form-label">API Token</label>
                    <input class="form-control" type="password" name="cpanel_api_token" placeholder="<?php echo !empty($settings['cpanel_api_token']) ? '•••••••• (saved - blank rehne dein badalna na ho to)' : 'cPanel API Token'; ?>">
                </div>
                <div class="form-group">
                    <label class="form-label">Document Root (jaha NeoPay already chal raha hai)</label>
                    <input class="form-control" type="text" name="cpanel_docroot" placeholder="neopay.mgamer.online" value="<?php echo htmlspecialchars($settings['cpanel_docroot'] ?? ''); ?>">
                    <div class="field-hint">cPanel home directory se relative path - File Manager me jo folder NeoPay ki files rakhta hai (jaise <code>neopay.mgamer.online</code>), uska exact naam.</div>
                </div>

                <button class="btn-primary-cta" type="submit"><i class="fas fa-floppy-disk"></i> Save Settings</button>
            </form>

            <div class="dashboard-card" style="margin-top:20px">
                <div class="card-header"><h3><i class="fas fa-paper-plane"></i> Send Test Email</h3></div>
                <div class="card-body">
                    <?php if ($testEmailMessage): ?>
                        <div style="background:<?php echo $testEmailMessage['type'] === 'success' ? 'rgba(67,233,123,.1)' : 'rgba(255,101,132,.1)'; ?>;color:<?php echo $testEmailMessage['type'] === 'success' ? '#43e97b' : '#ff6584'; ?>;border-radius:10px;padding:12px 16px;margin-bottom:16px;font-size:.85rem"><?php echo htmlspecialchars($testEmailMessage['text']); ?></div>
                    <?php endif; ?>
                    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" style="display:flex;gap:10px;flex-wrap:wrap">
                        <input class="form-control" type="email" name="test_email_to" placeholder="test@example.com" style="flex:1;min-width:200px" required>
                        <button class="btn-primary-cta" type="submit" name="sendTestEmail"><i class="fas fa-paper-plane"></i> Send Test</button>
                    </form>
                    <div class="field-hint" style="margin-top:10px">Pehle upar Save Settings zaroor dabayein, tabhi test email naye settings se jayega.</div>
                </div>
            </div>

            <div class="dashboard-card" style="margin-top:20px">
                <div class="card-header"><h3><i class="fas fa-percent"></i> Commission Settings</h3></div>
                <div class="card-body">
                    <p style="font-size:.8rem;color:rgba(255,255,255,.45);margin:0 0 16px">Har <b>successful</b> transaction pe merchant ke wallet se ye commission automatically cut hoga. Pending ya Failed orders pe kabhi nahi.</p>
                    <?php if ($commissionMessage):
                        $isErr = ($commissionMessage['type'] ?? '') === 'error';
                        $boxColor = $isErr ? '#ff6584' : '#43e97b';
                    ?>
                        <div style="background:<?php echo $isErr ? 'rgba(255,101,132,.1)' : 'rgba(67,233,123,.1)'; ?>;color:<?php echo $boxColor; ?>;border-radius:10px;padding:12px 16px;margin-bottom:16px;font-size:.85rem"><?php echo htmlspecialchars($commissionMessage['text']); ?></div>
                    <?php endif; ?>
                    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" style="display:flex;gap:12px;flex-wrap:wrap;align-items:flex-end">
                        <div style="min-width:160px">
                            <label class="field-label">Type</label>
                            <select class="form-control" name="commission_type">
                                <option value="percent" <?php echo ($settings['commission_type'] ?? 'percent') === 'percent' ? 'selected' : ''; ?>>Percentage (%)</option>
                                <option value="fixed" <?php echo ($settings['commission_type'] ?? '') === 'fixed' ? 'selected' : ''; ?>>Fixed Amount (₹)</option>
                            </select>
                        </div>
                        <div style="min-width:160px">
                            <label class="field-label">Value</label>
                            <input class="form-control" type="number" step="0.01" min="0" name="commission_value" value="<?php echo htmlspecialchars($settings['commission_value'] ?? '0'); ?>">
                        </div>
                        <div style="min-width:140px">
                            <label class="field-label">Min Add Funds (₹)</label>
                            <input class="form-control" type="number" step="0.01" min="1" name="wallet_topup_min" value="<?php echo htmlspecialchars($settings['wallet_topup_min'] ?? '10'); ?>">
                        </div>
                        <div style="min-width:140px">
                            <label class="field-label">Max Add Funds (₹)</label>
                            <input class="form-control" type="number" step="0.01" min="1" name="wallet_topup_max" value="<?php echo htmlspecialchars($settings['wallet_topup_max'] ?? '50000'); ?>">
                        </div>
                        <button class="btn-primary-cta" type="submit" name="saveCommission"><i class="fas fa-floppy-disk"></i> Save Commission</button>
                    </form>
                    <div class="field-hint" style="margin-top:10px">Example: <b>Percentage</b> 2 → ₹100 ka order pe ₹2 cut. <b>Fixed</b> 2 → har success order pe flat ₹2 cut, chahe amount kuch bhi ho. Min/Max sirf <b>Add Funds</b> (wallet top-up) pe apply hote hain.</div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
$cronJobsRes = mysqli_query($conn, "SELECT * FROM cron_jobs ORDER BY id ASC");
$cronJobs = [];
if ($cronJobsRes) { while ($r = mysqli_fetch_assoc($cronJobsRes)) { $cronJobs[] = $r; } }
$cronBaseUrl = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
?>
<div class="glass-card" id="cron-jobs" style="margin-top:24px">
    <div class="card-header"><h3><i class="fas fa-clock-rotate-left"></i> Cron Jobs</h3></div>
    <div class="card-body">
        <?php if (empty($cronJobs)): ?>
            <p style="font-size:.82rem;color:rgba(255,255,255,.45)">Cron jobs table nahi mili — <code>sql/cron_jobs_upgrade.sql</code> phpMyAdmin me run karein.</p>
        <?php else: ?>
            <p style="font-size:.8rem;color:rgba(255,255,255,.45);margin:0 0 16px">Yeh sab background tasks hain. cPanel ke <b>Cron Jobs</b> section me naya cron banate waqt "URL" nahi, ek <b>Command</b> field milegi — usme neeche di gayi command hoobahoo paste karein (URL akela paste karne se cron kaam nahi karega). Yahan se aap sirf on/off kar sakte hain.</p>
            <div class="cron-list">
                <?php foreach ($cronJobs as $job):
                    $fullUrl = $cronBaseUrl . ltrim($job['script_path'], '/');
                    $cronCommand = 'wget -q -O /dev/null "' . $fullUrl . '"';
                    $isOn = ((int)$job['is_enabled']) === 1;

                    // Rough "is this actually set up in cPanel" signal, based on
                    // whether/when it last actually ran (recorded by the script
                    // itself via cron_mark_ran()).
                    if (empty($job['last_run_at'])) {
                        $setupState = 'never';
                    } else {
                        $minsAgo = (strtotime(date('Y-m-d H:i:s')) - strtotime($job['last_run_at'])) / 60;
                        $setupState = ($minsAgo <= 180) ? 'running' : 'stale';
                    }
                ?>
                <div class="cron-row">
                    <div class="cron-info">
                        <div class="cron-name"><?php echo htmlspecialchars($job['name']); ?>
                            <span class="cron-badge <?php echo $isOn ? 'on' : 'off'; ?>"><?php echo $isOn ? 'Active' : 'Inactive'; ?></span>
                            <?php if ($setupState === 'never'): ?>
                                <span class="cron-badge setup-warn"><i class="fas fa-triangle-exclamation"></i> cPanel me setup nahi hai</span>
                            <?php elseif ($setupState === 'stale'): ?>
                                <span class="cron-badge setup-warn"><i class="fas fa-triangle-exclamation"></i> Ruka hua lagta hai</span>
                            <?php else: ?>
                                <span class="cron-badge setup-ok"><i class="fas fa-circle-check"></i> Chal raha hai</span>
                            <?php endif; ?>
                        </div>
                        <?php if (!empty($job['description'])): ?><div class="cron-desc"><?php echo htmlspecialchars($job['description']); ?></div><?php endif; ?>
                        <div class="cron-meta">
                            <span><i class="fas fa-repeat"></i> <?php echo htmlspecialchars($job['recommended_frequency'] ?: '—'); ?></span>
                            <span><i class="fas fa-clock"></i> Last run: <?php echo !empty($job['last_run_at']) ? htmlspecialchars($job['last_run_at']) : 'Never'; ?></span>
                        </div>
                        <div class="cron-url-row">
                            <code id="cronUrl-<?php echo htmlspecialchars($job['job_key']); ?>"><?php echo htmlspecialchars($cronCommand); ?></code>
                            <button type="button" class="copy-btn" onclick="copyCronUrl('<?php echo htmlspecialchars($job['job_key']); ?>')"><i class="fas fa-copy"></i></button>
                        </div>
                    </div>
                    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>#cron-jobs">
                        <input type="hidden" name="job_key" value="<?php echo htmlspecialchars($job['job_key']); ?>">
                        <input type="hidden" name="toggleCron" value="<?php echo $isOn ? 'disable' : 'enable'; ?>">
                        <button type="submit" class="cron-toggle-btn <?php echo $isOn ? 'is-on' : ''; ?>"><span class="cron-toggle-dot"></span></button>
                    </form>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>
<style>
    .cron-badge.setup-ok{background:rgba(67,233,123,.15);color:#43e97b}
    .cron-badge.setup-warn{background:rgba(245,185,59,.15);color:#f5b93b}
    .cron-list{display:flex;flex-direction:column;gap:12px}
    .cron-row{display:flex;align-items:flex-start;justify-content:space-between;gap:14px;background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.07);border-radius:12px;padding:14px 16px}
    .cron-info{flex:1;min-width:0}
    .cron-name{font-size:.9rem;font-weight:700;color:#fff;display:flex;align-items:center;gap:8px;flex-wrap:wrap}
    .cron-badge{font-size:.65rem;font-weight:700;padding:2px 8px;border-radius:20px;text-transform:uppercase}
    .cron-badge.on{background:rgba(67,233,123,.15);color:#43e97b}
    .cron-badge.off{background:rgba(255,101,132,.15);color:#ff6584}
    .cron-desc{font-size:.76rem;color:rgba(255,255,255,.45);margin-top:4px}
    .cron-meta{display:flex;gap:16px;flex-wrap:wrap;font-size:.72rem;color:rgba(255,255,255,.4);margin-top:8px}
    .cron-meta i{margin-right:4px}
    .cron-url-row{display:flex;align-items:center;gap:8px;margin-top:8px;background:rgba(0,0,0,.25);border:1px solid rgba(255,255,255,.08);border-radius:8px;padding:6px 10px;flex-wrap:wrap}
    .cron-url-row code{background:none;padding:0;font-size:.7rem;color:#43e97b;word-break:break-all;flex:1}
    .cron-toggle-btn{width:46px;height:26px;border-radius:20px;border:none;background:rgba(255,255,255,.15);position:relative;cursor:pointer;flex-shrink:0;transition:.2s}
    .cron-toggle-btn.is-on{background:var(--g)}
    .cron-toggle-dot{position:absolute;top:3px;left:3px;width:20px;height:20px;border-radius:50%;background:#fff;transition:.2s}
    .cron-toggle-btn.is-on .cron-toggle-dot{left:23px}
</style>
<script>
function copyCronUrl(key) {
    var text = document.getElementById('cronUrl-' + key).textContent;
    navigator.clipboard.writeText(text).then(function() {
        Swal.fire({ title: 'Copied!', icon: 'success', background: '#14141f', color: '#fff', timer: 1200, showConfirmButton: false });
    });
}
</script>

<?php } ?>
<!-- Include necessary scripts -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>
<script src="./assets/vendors/jquery/dist/jquery.min.js" type="text/javascript"></script>
<script src="assets/js/app.min.js" type="text/javascript"></script>
<script src="./assets/js/scripts/dashboard_1_demo.js" type="text/javascript"></script>
<script>
    function updateLogoPreview(url) {
        var box = document.getElementById('logoPreview');
        if (!url) { box.innerHTML = '<i class="fas fa-image"></i>'; return; }
        box.innerHTML = '<img src="' + url + '" onerror="this.parentNode.innerHTML=\'<i class=\\\'fas fa-triangle-exclamation\\\' style=\\\'color:#ff6584\\\'></i>\'">';
    }
    var logoInput = document.getElementById('logoUrlInput');
    if (logoInput) {
        updateLogoPreview(logoInput.value);
        logoInput.addEventListener('input', function() { updateLogoPreview(this.value); });
    }

    function copyRedirectUri() {
        var text = document.getElementById('redirectUriHint').textContent;
        navigator.clipboard.writeText(text).then(function() {
            Swal.fire({
                title: 'Copied!',
                text: 'Redirect URI clipboard me copy ho gayi.',
                icon: 'success',
                background: '#14141f',
                color: '#fff',
                timer: 1500,
                showConfirmButton: false
            });
        });
    }

    <?php if (isset($_GET['message'])): ?>
    Swal.fire({
        title: 'Saved!',
        text: '<?php echo addslashes($_GET['message']); ?>',
        icon: '<?php echo (stripos($_GET['message'], 'error') !== false) ? 'error' : 'success'; ?>',
        confirmButtonText: 'OK',
        background: '#14141f',
        color: '#fff',
        timer: 2500
    }).then(function() {
        var url = new URL(window.location.href);
        url.searchParams.delete('message');
        window.history.replaceState({}, document.title, url.toString());
    });
    <?php endif; ?>
</script>
</body>
</html>
