<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (file_exists($config_path)) {
    include($config_path);
} else {
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}

header('Content-Type: application/json; charset=utf-8');

// Auth: must be logged in
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized access']);
    exit();
}

// Auth: must be admin
try {
    $stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :user_id");
    $stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
    $stmt->execute();
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$admin || $admin['is_admin'] != 1) {
        echo json_encode(['status' => '0', 'msg' => 'Unauthorized access']);
        exit();
    }
} catch (PDOException $e) {
    echo json_encode(['status' => '0', 'msg' => 'Authentication error']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
    exit();
}

$action = trim($_POST['action'] ?? '');

// ════════════════════════════════════════════════════════════════
// ACTION: Save Module Toggles
// ════════════════════════════════════════════════════════════════
if ($action === 'save_module_toggles') {
    $module_keys = [
        'module_virtual_numbers',
        'module_smm',
        'module_buy_data',
        'module_buy_airtime',
        'module_cable_tv',
        'module_electricity',
        'module_buy_giftcard',
        'module_sell_giftcard',
        'module_virtual_cards',
        'module_marketplace',
        'module_sell_account',
        'module_referral',
        'module_withdraw',
        'module_buy_logs',
    ];

    $updates = [];
    $params  = [];
    foreach ($module_keys as $key) {
        $updates[] = "$key = :$key";
        $params[$key] = isset($_POST[$key]) ? 1 : 0;
    }

    try {
        $sql = "UPDATE settings SET " . implode(', ', $updates) . " WHERE id = 1";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        echo json_encode(['status' => '1', 'msg' => 'Module settings saved successfully!']);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: Sync JAP Services
// ════════════════════════════════════════════════════════════════
if ($action === 'sync_jap_services') {
    $api_key = trim($_POST['jap_api_key'] ?? '');
    $api_url = trim($_POST['jap_api_url'] ?? 'https://the-owlet.com/api/v2');

    if (empty($api_key)) {
        echo json_encode(['status' => '0', 'msg' => 'JAP API key is required.']);
        exit();
    }

    $jap_path = dirname(__DIR__, 2) . '/include/JAP.php';
    if (!file_exists($jap_path)) {
        echo json_encode(['status' => '0', 'msg' => 'JAP.php not found in include/ folder.']);
        exit();
    }
    require_once $jap_path;

    $jap = new JAP($api_key, $api_url);
    $res = $jap->getServices();

    if (!$res['success']) {
        echo json_encode(['status' => '0', 'msg' => 'JAP API error: ' . ($res['error'] ?? 'Unknown error')]);
        exit();
    }

    $services = $res['data'];
    if (empty($services) || !is_array($services)) {
        echo json_encode(['status' => '0', 'msg' => 'No services returned from JAP.']);
        exit();
    }

    $site   = $pdo->query("SELECT smm_markup FROM settings WHERE id = 1")->fetch(PDO::FETCH_ASSOC);
    $markup = (float)($site['smm_markup'] ?? 30);
    $inserted = 0;
    $updated  = 0;

    foreach ($services as $s) {
        $jap_rate = (float)($s['rate']  ?? 0);
        $our_rate = round($jap_rate * (1 + $markup / 100), 2);
        $jap_id   = (int)($s['service'] ?? 0);
        $category = $s['category']       ?? 'General';
        $name     = $s['name']           ?? '';
        $type     = $s['type']           ?? 'Default';
        $min      = (int)($s['min']      ?? 10);
        $max      = (int)($s['max']      ?? 1000000);
        $refill   = !empty($s['refill']) ? 1 : 0;
        $cancel   = !empty($s['cancel']) ? 1 : 0;

        if (!$jap_id || empty($name)) continue;

        $exists = $pdo->prepare("SELECT id FROM smm_services WHERE jap_service_id = :jid LIMIT 1");
        $exists->execute(['jid' => $jap_id]);
        $row = $exists->fetch();

        if ($row) {
            $pdo->prepare("UPDATE smm_services SET category=:cat, name=:name, type=:type, jap_rate=:jrate,
                min_quantity=:min, max_quantity=:max, refill=:refill, cancel=:cancel, updated_at=NOW()
                WHERE jap_service_id=:jid")
                ->execute(['cat'=>$category,'name'=>$name,'type'=>$type,'jrate'=>$jap_rate,
                           'min'=>$min,'max'=>$max,'refill'=>$refill,'cancel'=>$cancel,'jid'=>$jap_id]);
            $updated++;
        } else {
            $pdo->prepare("INSERT INTO smm_services
                (jap_service_id,category,name,type,jap_rate,our_rate,min_quantity,max_quantity,refill,cancel,status)
                VALUES(:jid,:cat,:name,:type,:jrate,:orate,:min,:max,:refill,:cancel,1)")
                ->execute(['jid'=>$jap_id,'cat'=>$category,'name'=>$name,'type'=>$type,
                           'jrate'=>$jap_rate,'orate'=>$our_rate,'min'=>$min,'max'=>$max,
                           'refill'=>$refill,'cancel'=>$cancel]);
            $inserted++;
        }
    }

    echo json_encode(['status'=>'1','msg'=>"<strong>{$inserted}</strong> new services added, <strong>{$updated}</strong> updated."]);
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: Recalculate Rates
// ════════════════════════════════════════════════════════════════
if ($action === 'recalculate_rates') {
    $markup = (float)($_POST['smm_markup'] ?? 30);

    $pdo->prepare("UPDATE settings SET smm_markup=:markup WHERE id=1")->execute(['markup' => $markup]);

    $all   = $pdo->query("SELECT id, jap_rate FROM smm_services")->fetchAll(PDO::FETCH_ASSOC);
    $count = 0;
    foreach ($all as $s) {
        $new_rate = round((float)$s['jap_rate'] * (1 + $markup / 100), 2);
        $pdo->prepare("UPDATE smm_services SET our_rate=:r WHERE id=:id")->execute(['r' => $new_rate, 'id' => $s['id']]);
        $count++;
    }

    echo json_encode(['status'=>'1','msg'=>"{$count} service prices updated. Markup: {$markup}%"]);
    exit();
}


// ════════════════════════════════════════════════════════════════
// ACTION: Sync Prices — Fetch latest JAP rates + apply markup
// Updates our_rate on all existing services from live API prices
// Also records last_price_sync timestamp in settings
// ════════════════════════════════════════════════════════════════
if ($action === 'sync_prices') {
    $api_key = trim($_POST['jap_api_key'] ?? '');
    $api_url = trim($_POST['jap_api_url'] ?? 'https://the-owlet.com/api/v2');
    $markup  = (float)($_POST['smm_markup'] ?? 30);

    if (empty($api_key)) {
        echo json_encode(['status' => '0', 'msg' => 'JAP API key is required.']);
        exit();
    }

    $jap_path = dirname(__DIR__, 2) . '/include/JAP.php';
    if (!file_exists($jap_path)) {
        echo json_encode(['status' => '0', 'msg' => 'JAP.php not found in include/ folder.']);
        exit();
    }
    require_once $jap_path;

    // Fetch latest service list from JAP
    $jap = new JAP($api_key, $api_url);
    $res = $jap->getServices();

    if (!$res['success']) {
        echo json_encode(['status' => '0', 'msg' => 'JAP API error: ' . ($res['error'] ?? 'Unknown error')]);
        exit();
    }

    $services = $res['data'];
    if (empty($services) || !is_array($services)) {
        echo json_encode(['status' => '0', 'msg' => 'No services returned from JAP API.']);
        exit();
    }

    $updated  = 0;
    $skipped  = 0; // services in JAP but not yet in our DB (not inserted, only prices updated)
    $no_match = 0;

    // Prepare update statement — only update jap_rate + our_rate for EXISTING services
    $stmt = $pdo->prepare(
        "UPDATE smm_services
            SET jap_rate  = :jap_rate,
                our_rate  = :our_rate,
                updated_at = NOW()
          WHERE jap_service_id = :jap_id"
    );

    foreach ($services as $s) {
        $jap_id   = (int)($s['service'] ?? 0);
        $jap_rate = (float)($s['rate']   ?? 0);

        if (!$jap_id) continue;

        $our_rate = round($jap_rate * (1 + $markup / 100), 2);

        $stmt->execute([
            'jap_rate' => $jap_rate,
            'our_rate' => $our_rate,
            'jap_id'   => $jap_id,
        ]);

        $rows = $stmt->rowCount();
        if ($rows > 0) {
            $updated++;
        } else {
            $no_match++; // service exists on JAP but not in our smm_services table yet
        }
    }

    // Save the markup (in case it changed) and record sync timestamp
    $pdo->prepare(
        "UPDATE settings SET smm_markup = :markup, last_price_sync = NOW() WHERE id = 1"
    )->execute(['markup' => $markup]);

    // Get the formatted timestamp to return to frontend
    $sync_row  = $pdo->query("SELECT last_price_sync FROM settings WHERE id = 1")->fetch(PDO::FETCH_ASSOC);
    $sync_time = !empty($sync_row['last_price_sync'])
        ? date('d M Y, h:i A', strtotime($sync_row['last_price_sync']))
        : date('d M Y, h:i A');

    $msg = "<strong>{$updated}</strong> service price(s) updated with <strong>{$markup}%</strong> markup.";
    if ($no_match > 0) {
        $msg .= "<br><small class='text-muted'>{$no_match} JAP service(s) not in your DB yet — run <strong>Sync Services</strong> to import them.</small>";
    }

    echo json_encode([
        'status'    => '1',
        'msg'       => $msg,
        'updated'   => $updated,
        'no_match'  => $no_match,
        'last_sync' => $sync_time,
    ]);
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: Save SMS-Man Settings (quick save, not full form)
// ════════════════════════════════════════════════════════════════
if ($action === 'save_smsman_settings') {
    $api_url   = trim($_POST['smsman_api_url']   ?? 'https://api.sms-man.com/control');
    $api_token = trim($_POST['smsman_api_token'] ?? '');
    $markup    = (float)($_POST['smsman_markup'] ?? 30);

    if (empty($api_token)) {
        echo json_encode(['status' => '0', 'msg' => 'API token is required.']);
        exit();
    }

    try {
        $count = (int)$pdo->query("SELECT COUNT(*) FROM settings")->fetchColumn();
        if ($count > 0) {
            $pdo->prepare("UPDATE settings SET smsman_api_url=:url, smsman_api_token=:tok, smsman_markup=:mkp WHERE id=1")
                ->execute(['url' => $api_url, 'tok' => $api_token, 'mkp' => $markup]);
        } else {
            $pdo->prepare("INSERT INTO settings (smsman_api_url, smsman_api_token, smsman_markup) VALUES (:url,:tok,:mkp)")
                ->execute(['url' => $api_url, 'tok' => $api_token, 'mkp' => $markup]);
        }
        echo json_encode(['status' => '1', 'msg' => 'SMS-Man settings saved successfully.']);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: Test SMS-Man Connection
// ════════════════════════════════════════════════════════════════
if ($action === 'check_smsman_balance') {
    $smsman_path = dirname(__DIR__, 2) . '/include/SMSMan.php';
    if (!file_exists($smsman_path)) {
        echo json_encode(['status' => '0', 'msg' => 'SMSMan.php not found. Upload include/SMSMan.php first.']);
        exit();
    }
    require_once $smsman_path;

    // Accept token from POST (test before saving) or fall back to DB
    $token    = trim($_POST['smsman_api_token'] ?? '');
    $base_url = trim($_POST['smsman_api_url']   ?? '');

    if (empty($token)) {
        $row      = $pdo->query("SELECT smsman_api_token, smsman_api_url FROM settings WHERE id=1")->fetch(PDO::FETCH_ASSOC);
        $token    = $row['smsman_api_token'] ?? '';
        $base_url = $row['smsman_api_url']   ?? 'https://api.sms-man.com/control';
    }
    if (empty($base_url)) {
        $base_url = 'https://api.sms-man.com/control';
    }

    if (empty($token)) {
        echo json_encode(['status' => '0', 'msg' => 'No API token found. Enter your token and click Save Settings first.']);
        exit();
    }

    $smsman = new SMSMan($token, $base_url);
    $r      = $smsman->getBalance();

    if ($r['success']) {
        echo json_encode(['status' => '1', 'balance' => $r['data']['balance'] ?? '0']);
    } else {
        echo json_encode(['status' => '0', 'msg' => 'API error: ' . ($r['error_msg'] ?? 'Invalid token or URL.')]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: Sync SMS-Man Countries
// ════════════════════════════════════════════════════════════════
if ($action === 'sync_smsman_countries') {
    $smsman_path = dirname(__DIR__, 2) . '/include/SMSMan.php';
    if (!file_exists($smsman_path)) {
        echo json_encode(['status' => '0', 'msg' => 'SMSMan.php not found in include/ folder.']); exit();
    }
    require_once $smsman_path;

    $row      = $pdo->query("SELECT smsman_api_token, smsman_api_url FROM settings WHERE id=1")->fetch(PDO::FETCH_ASSOC);
    $token    = $row['smsman_api_token'] ?? '';
    $base_url = $row['smsman_api_url']   ?? 'https://api.sms-man.com/control';

    if (empty($token)) {
        echo json_encode(['status' => '0', 'msg' => 'API token not saved. Click "Save Settings" in the SMS-Man card first.']); exit();
    }

    $smsman = new SMSMan($token, $base_url);
    $r      = $smsman->getCountries();

    if (!$r['success']) {
        echo json_encode(['status' => '0', 'msg' => 'SMS-Man API error: ' . ($r['error_msg'] ?? 'Unknown')]); exit();
    }
    if (empty($r['data']) || !is_array($r['data'])) {
        echo json_encode(['status' => '0', 'msg' => 'No countries returned from API.']); exit();
    }

    $inserted = 0; $updated = 0;
    $stmt = $pdo->prepare("INSERT INTO smsman_countries (id, title)
        VALUES (:id, :title)
        ON DUPLICATE KEY UPDATE title=VALUES(title), updated_at=NOW()");

    foreach ($r['data'] as $c) {
        $cid   = (int)($c['id']   ?? 0);
        $title = trim($c['title'] ?? '');
        if (!$cid || !$title) continue;
        $stmt->execute(['id' => $cid, 'title' => $title]);
        $rc = $stmt->rowCount();
        if ($rc == 1)      $inserted++;
        elseif ($rc >= 2)  $updated++;
    }

    echo json_encode([
        'status'   => '1',
        'msg'      => "Countries synced: {$inserted} new, {$updated} updated.",
        'total'    => count($r['data']),
        'inserted' => $inserted,
        'updated'  => $updated,
    ]);
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: Sync SMS-Man Applications
// ════════════════════════════════════════════════════════════════
if ($action === 'sync_smsman_apps') {
    $smsman_path = dirname(__DIR__, 2) . '/include/SMSMan.php';
    if (!file_exists($smsman_path)) {
        echo json_encode(['status' => '0', 'msg' => 'SMSMan.php not found in include/ folder.']); exit();
    }
    require_once $smsman_path;

    $row      = $pdo->query("SELECT smsman_api_token, smsman_api_url FROM settings WHERE id=1")->fetch(PDO::FETCH_ASSOC);
    $token    = $row['smsman_api_token'] ?? '';
    $base_url = $row['smsman_api_url']   ?? 'https://api.sms-man.com/control';

    if (empty($token)) {
        echo json_encode(['status' => '0', 'msg' => 'API token not saved. Click "Save Settings" in the SMS-Man card first.']); exit();
    }

    $smsman = new SMSMan($token, $base_url);
    $r      = $smsman->getApplications();

    if (!$r['success']) {
        echo json_encode(['status' => '0', 'msg' => 'SMS-Man API error: ' . ($r['error_msg'] ?? 'Unknown')]); exit();
    }
    if (empty($r['data']) || !is_array($r['data'])) {
        echo json_encode(['status' => '0', 'msg' => 'No applications returned from API.']); exit();
    }

    $inserted = 0; $updated = 0;
    $stmt = $pdo->prepare("INSERT INTO smsman_applications (id, name, code)
        VALUES (:id, :name, :code)
        ON DUPLICATE KEY UPDATE name=VALUES(name), code=VALUES(code), updated_at=NOW()");

    foreach ($r['data'] as $a) {
        $aid  = (int)($a['id']  ?? 0);
        $name = trim($a['name'] ?? '');
        $code = trim($a['code'] ?? '');
        if (!$aid || !$name) continue;
        $stmt->execute(['id' => $aid, 'name' => $name, 'code' => $code]);
        $rc = $stmt->rowCount();
        if ($rc == 1)     $inserted++;
        elseif ($rc >= 2) $updated++;
    }

    echo json_encode([
        'status'   => '1',
        'msg'      => "Services synced: {$inserted} new, {$updated} updated.",
        'total'    => count($r['data']),
        'inserted' => $inserted,
        'updated'  => $updated,
    ]);
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: Sync SMS-Man All (Countries + Applications)
// ════════════════════════════════════════════════════════════════
if ($action === 'sync_smsman_all') {
    $smsman_path = dirname(__DIR__, 2) . '/include/SMSMan.php';
    if (!file_exists($smsman_path)) {
        echo json_encode(['status' => '0', 'msg' => 'SMSMan.php not found in include/ folder.']); exit();
    }
    require_once $smsman_path;

    $row      = $pdo->query("SELECT smsman_api_token, smsman_api_url FROM settings WHERE id=1")->fetch(PDO::FETCH_ASSOC);
    $token    = $row['smsman_api_token'] ?? '';
    $base_url = $row['smsman_api_url']   ?? 'https://api.sms-man.com/control';

    if (empty($token)) {
        echo json_encode(['status' => '0', 'msg' => 'API token not saved. Click "Save Settings" in the SMS-Man card first, then sync.']); exit();
    }

    $smsman  = new SMSMan($token, $base_url);
    $results = [];

    // Countries
    $rc = $smsman->getCountries();
    if ($rc['success'] && is_array($rc['data']) && !empty($rc['data'])) {
        $ins = 0; $upd = 0;
        $sc  = $pdo->prepare("INSERT INTO smsman_countries (id, title)
            VALUES (:id, :title)
            ON DUPLICATE KEY UPDATE title=VALUES(title), updated_at=NOW()");
        foreach ($rc['data'] as $c) {
            $cid = (int)($c['id'] ?? 0); $title = trim($c['title'] ?? '');
            if (!$cid || !$title) continue;
            $sc->execute(['id' => $cid, 'title' => $title]);
            $cnt = $sc->rowCount();
            if ($cnt == 1) $ins++; elseif ($cnt >= 2) $upd++;
        }
        $results['countries'] = ['total' => count($rc['data']), 'inserted' => $ins, 'updated' => $upd];
    } else {
        $results['countries'] = ['error' => $rc['error_msg'] ?? 'Failed'];
    }

    // Applications
    $ra = $smsman->getApplications();
    if ($ra['success'] && is_array($ra['data']) && !empty($ra['data'])) {
        $ins = 0; $upd = 0;
        $sa  = $pdo->prepare("INSERT INTO smsman_applications (id, name, code)
            VALUES (:id, :name, :code)
            ON DUPLICATE KEY UPDATE name=VALUES(name), code=VALUES(code), updated_at=NOW()");
        foreach ($ra['data'] as $a) {
            $aid = (int)($a['id'] ?? 0); $name = trim($a['name'] ?? ''); $code = trim($a['code'] ?? '');
            if (!$aid || !$name) continue;
            $sa->execute(['id' => $aid, 'name' => $name, 'code' => $code]);
            $cnt = $sa->rowCount();
            if ($cnt == 1) $ins++; elseif ($cnt >= 2) $upd++;
        }
        $results['apps'] = ['total' => count($ra['data']), 'inserted' => $ins, 'updated' => $upd];
    } else {
        $results['apps'] = ['error' => $ra['error_msg'] ?? 'Failed'];
    }

    $cTotal = $results['countries']['total'] ?? 0;
    $aTotal = $results['apps']['total']      ?? 0;

    echo json_encode([
        'status'  => '1',
        'msg'     => "Sync complete! {$cTotal} countries and {$aTotal} services synced.",
        'results' => $results,
    ]);
    exit();
}

// ════════════════════════════════════════════════════════════════
// DEFAULT: Save All Settings (main form submit)
// ════════════════════════════════════════════════════════════════

// Handle logo file upload
$upload_dir = dirname(__DIR__, 2) . '/images/';
if (!is_dir($upload_dir)) { mkdir($upload_dir, 0755, true); }

$logo_url_value = trim($_POST['logo_url'] ?? '');
if (!empty($_FILES['logo_file']['name']) && $_FILES['logo_file']['error'] === UPLOAD_ERR_OK) {
    $ext = strtolower(pathinfo($_FILES['logo_file']['name'], PATHINFO_EXTENSION));
    if (in_array($ext, ['png','jpg','jpeg','gif','svg','webp','ico'])) {
        $filename = 'logo_' . time() . '.' . $ext;
        if (move_uploaded_file($_FILES['logo_file']['tmp_name'], $upload_dir . $filename)) {
            $web_url = trim($_POST['web_url'] ?? '');
            $logo_url_value = $web_url . '/images/' . $filename;
        }
    }
}

$favicon_url_value = trim($_POST['favicon_url'] ?? '');
if (!empty($_FILES['favicon_file']['name']) && $_FILES['favicon_file']['error'] === UPLOAD_ERR_OK) {
    $ext = strtolower(pathinfo($_FILES['favicon_file']['name'], PATHINFO_EXTENSION));
    if (in_array($ext, ['png','jpg','jpeg','gif','svg','webp','ico'])) {
        $filename = 'favicon_' . time() . '.' . $ext;
        if (move_uploaded_file($_FILES['favicon_file']['tmp_name'], $upload_dir . $filename)) {
            $web_url = trim($_POST['web_url'] ?? '');
            $favicon_url_value = $web_url . '/images/' . $filename;
        }
    }
}

$settings = [
    'web_name'                       => trim($_POST['web_name']           ?? ''),
    'web_url'                        => trim($_POST['web_url']            ?? ''),
    'logo_url'                       => $logo_url_value,
    'favicon_url'                    => $favicon_url_value,
    'web_email'                      => trim($_POST['web_email']          ?? ''),
    'currency'                       => trim($_POST['currency']           ?? ''),
    'web_telegram'                   => trim($_POST['web_telegram']       ?? ''),
    'whatsapp_number'                => trim($_POST['whatsapp_number']    ?? ''),
    'support_url'                    => trim($_POST['support_url']        ?? ''),
    'channel_url'                    => trim($_POST['channel_url']        ?? ''),
    'web_facebook'                   => trim($_POST['web_facebook']       ?? ''),
    'web_x'                          => trim($_POST['web_x']              ?? ''),
    'web_instagram'                  => trim($_POST['web_instagram']      ?? ''),
    'web_tiktok'                     => trim($_POST['web_tiktok']         ?? ''),
    'web_youtube'                    => trim($_POST['web_youtube']        ?? ''),
    'refer_percent'                  => (float)($_POST['refer_percent']   ?? 0),
    'min_redeem'                     => (float)($_POST['min_redeem']      ?? 0),
    'marketplace_listing_fee'        => (float)($_POST['marketplace_listing_fee'] ?? 500),
    'seller_registration_fee'        => (float)($_POST['seller_registration_fee'] ?? 2000),
    // Paystack
    'paystack_enabled'               => isset($_POST['paystack_enabled']) ? 1 : 0,
    'paystack_public_key'            => trim($_POST['paystack_public_key']  ?? ''),
    'paystack_secret_key'            => trim($_POST['paystack_secret_key']  ?? ''),
    'paystack_minimum'               => (float)($_POST['paystack_minimum']  ?? 0),
    // Korapay
    'korapay_enabled'                => isset($_POST['korapay_enabled']) ? 1 : 0,
    'korapay_public_key'             => trim($_POST['korapay_public_key']   ?? ''),
    'korapay_secret_key'             => trim($_POST['korapay_secret_key']   ?? ''),
    'korapay_enc_key'                => trim($_POST['korapay_enc_key']      ?? ''),
    'korapay_minimum'                => (float)($_POST['korapay_minimum']   ?? 100),
    // Cryptomus
    'cryptomus_merchant_id'          => trim($_POST['cryptomus_merchant_id']  ?? ''),
    'cryptomus_payment_key'          => trim($_POST['cryptomus_payment_key']  ?? ''),
    'cryptomus_minimum'              => (float)($_POST['cryptomus_minimum']   ?? 1.00),
    'cryptomus_enabled'              => isset($_POST['cryptomus_enabled']) ? 1 : 0,
    'usd_to_ngn'                     => (float)($_POST['usd_to_ngn']          ?? 1600),
    // Pocketfi
    'pocketfi_api_key'               => trim($_POST['pocketfi_api_key']       ?? ''),
    'pocketfi_business_id'           => trim($_POST['pocketfi_business_id']   ?? ''),
    'pocketfi_bank'                  => trim($_POST['pocketfi_bank']          ?? 'kuda'),
    'pocketfi_api_url'               => trim($_POST['pocketfi_api_url']       ?? 'https://pocketfi.ng/api/v1'),
    'pocketfi_webhook_secret'        => trim($_POST['pocketfi_webhook_secret'] ?? ''),
    'pocketfi_enabled'               => isset($_POST['pocketfi_enabled']) ? 1 : 0,
    'pocketfi_bank_name'             => trim($_POST['pocketfi_bank_name']     ?? ''),
    // Security
    'captcha_public_key'             => trim($_POST['captcha_public_key'] ?? ''),
    'captcha_secret_key'             => trim($_POST['captcha_secret_key'] ?? ''),
    // Telegram
    'telegram_bot_token'             => trim($_POST['telegram_bot_token']         ?? ''),
    'telegram_admin_chat_id'         => trim($_POST['telegram_admin_chat_id']     ?? ''),
    'telegram_notifications_enabled' => isset($_POST['telegram_notifications_enabled']) ? 1 : 0,
    // JAP SMM
    'jap_api_key'                    => trim($_POST['jap_api_key']        ?? ''),
    'jap_api_url'                    => trim($_POST['jap_api_url']        ?? 'https://the-owlet.com/api/v2'),
    'smm_markup'                     => (float)($_POST['smm_markup']      ?? 30),
    // Sudo Africa
    'sudo_api_key'                   => trim($_POST['sudo_api_key']       ?? ''),
    'sudo_card_program'              => trim($_POST['sudo_card_program']  ?? ''),
    'card_creation_fee'              => (float)($_POST['card_creation_fee'] ?? 0),
    'sudo_sandbox'                   => isset($_POST['sudo_sandbox']) ? 1 : 0,
    'announcement'                   => trim($_POST['announcement']       ?? ''),
    'telegram_group_url'             => trim($_POST['telegram_group_url'] ?? ''),
    'withdraw_minimum'               => floatval($_POST['withdraw_minimum'] ?? 500),
    'withdraw_fee'                   => floatval($_POST['withdraw_fee'] ?? 50),
    'paystack_dva_enabled'           => isset($_POST['paystack_dva_enabled']) ? 1 : 0,
    'paystack_dva_provider'          => trim($_POST['paystack_dva_provider'] ?? 'wema-bank'),
    // Module Toggles
    'module_virtual_numbers'         => isset($_POST['module_virtual_numbers']) ? 1 : 0,
    'module_smm'                     => isset($_POST['module_smm']) ? 1 : 0,
    'module_buy_data'                => isset($_POST['module_buy_data']) ? 1 : 0,
    'module_buy_airtime'             => isset($_POST['module_buy_airtime']) ? 1 : 0,
    'module_cable_tv'                => isset($_POST['module_cable_tv']) ? 1 : 0,
    'module_electricity'             => isset($_POST['module_electricity']) ? 1 : 0,
    'module_buy_giftcard'            => isset($_POST['module_buy_giftcard']) ? 1 : 0,
    'module_sell_giftcard'           => isset($_POST['module_sell_giftcard']) ? 1 : 0,
    'module_virtual_cards'           => isset($_POST['module_virtual_cards']) ? 1 : 0,
    'module_marketplace'             => isset($_POST['module_marketplace']) ? 1 : 0,
    'module_sell_account'            => isset($_POST['module_sell_account']) ? 1 : 0,
    'module_referral'                => isset($_POST['module_referral']) ? 1 : 0,
    'module_withdraw'                => isset($_POST['module_withdraw']) ? 1 : 0,
    'module_buy_logs'                => isset($_POST['module_buy_logs']) ? 1 : 0,

];

if (empty($settings['web_name']) || empty($settings['web_url']) || empty($settings['web_email'])) {
    echo json_encode(['status' => '0', 'msg' => 'Website name, URL, and email are required']);
    exit();
}
if (!filter_var($settings['web_email'], FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['status' => '0', 'msg' => 'Invalid email format']);
    exit();
}

try {
    $count = (int)$pdo->query("SELECT COUNT(*) FROM settings")->fetchColumn();

    if ($count == 0) {
        $sql = "INSERT INTO settings (
            web_name, web_url, logo_url, favicon_url, web_email, currency,
            web_telegram, whatsapp_number, support_url, channel_url, web_facebook, web_x,
            web_instagram, web_tiktok, web_youtube, refer_percent, min_redeem,
            marketplace_listing_fee,
            seller_registration_fee,
            paystack_public_key, paystack_secret_key, paystack_minimum,
            paystack_enabled,
            korapay_public_key, korapay_secret_key, korapay_enc_key, korapay_minimum,
            korapay_enabled,
            cryptomus_merchant_id, cryptomus_payment_key, cryptomus_minimum, cryptomus_enabled, usd_to_ngn,
            pocketfi_api_key, pocketfi_business_id, pocketfi_bank, pocketfi_api_url, pocketfi_webhook_secret, pocketfi_enabled, pocketfi_bank_name,
            captcha_public_key, captcha_secret_key,
            telegram_bot_token, telegram_admin_chat_id, telegram_notifications_enabled,
            jap_api_key, jap_api_url, smm_markup,
            sudo_api_key, sudo_card_program, card_creation_fee, sudo_sandbox,
            module_virtual_numbers, module_smm, module_buy_data, module_buy_airtime,
            module_cable_tv, module_electricity, module_buy_giftcard, module_sell_giftcard,
            module_virtual_cards, module_marketplace, module_sell_account, module_referral,
            module_withdraw, module_buy_logs
        ) VALUES (
            :web_name, :web_url, :logo_url, :favicon_url, :web_email, :currency,
            :web_telegram, :whatsapp_number, :support_url, :channel_url, :web_facebook, :web_x,
            :web_instagram, :web_tiktok, :web_youtube, :refer_percent, :min_redeem,
            :marketplace_listing_fee,
            :seller_registration_fee,
            :paystack_public_key, :paystack_secret_key, :paystack_minimum,
            :paystack_enabled,
            :korapay_public_key, :korapay_secret_key, :korapay_enc_key, :korapay_minimum,
            :korapay_enabled,
            :cryptomus_merchant_id, :cryptomus_payment_key, :cryptomus_minimum, :cryptomus_enabled, :usd_to_ngn,
            :pocketfi_api_key, :pocketfi_business_id, :pocketfi_bank, :pocketfi_api_url, :pocketfi_webhook_secret, :pocketfi_enabled, :pocketfi_bank_name,
            :captcha_public_key, :captcha_secret_key,
            :telegram_bot_token, :telegram_admin_chat_id, :telegram_notifications_enabled,
            :jap_api_key, :jap_api_url, :smm_markup,
            :sudo_api_key, :sudo_card_program, :card_creation_fee, :sudo_sandbox,
            :module_virtual_numbers, :module_smm, :module_buy_data, :module_buy_airtime,
            :module_cable_tv, :module_electricity, :module_buy_giftcard, :module_sell_giftcard,
            :module_virtual_cards, :module_marketplace, :module_sell_account, :module_referral,
            :module_withdraw, :module_buy_logs
        )";
    } else {
                $sql = "UPDATE settings SET
            web_name                       = :web_name,
            web_url                        = :web_url,
            logo_url                       = :logo_url,
            favicon_url                    = :favicon_url,
            web_email                      = :web_email,
            currency                       = :currency,
            web_telegram                   = :web_telegram,
            whatsapp_number                = :whatsapp_number,
            support_url                    = :support_url,
            channel_url                    = :channel_url,
            web_facebook                   = :web_facebook,
            web_x                          = :web_x,
            web_instagram                  = :web_instagram,
            web_tiktok                     = :web_tiktok,
            web_youtube                    = :web_youtube,
            refer_percent                  = :refer_percent,
            min_redeem                     = :min_redeem,
            marketplace_listing_fee        = :marketplace_listing_fee,
            seller_registration_fee        = :seller_registration_fee,
            paystack_public_key            = :paystack_public_key,
            paystack_secret_key            = :paystack_secret_key,
            paystack_minimum               = :paystack_minimum,
            paystack_enabled               = :paystack_enabled,
            korapay_public_key             = :korapay_public_key,
            korapay_secret_key             = :korapay_secret_key,
            korapay_enc_key                = :korapay_enc_key,
            korapay_minimum                = :korapay_minimum,
            korapay_enabled                = :korapay_enabled,
            cryptomus_merchant_id          = :cryptomus_merchant_id,
            cryptomus_payment_key          = :cryptomus_payment_key,
            cryptomus_minimum              = :cryptomus_minimum,
            cryptomus_enabled              = :cryptomus_enabled,
            usd_to_ngn                     = :usd_to_ngn,
            pocketfi_api_key               = :pocketfi_api_key,
            pocketfi_business_id           = :pocketfi_business_id,
            pocketfi_bank                  = :pocketfi_bank,
            pocketfi_api_url               = :pocketfi_api_url,
            pocketfi_webhook_secret        = :pocketfi_webhook_secret,
            pocketfi_enabled               = :pocketfi_enabled,
            pocketfi_bank_name             = :pocketfi_bank_name,
            captcha_public_key             = :captcha_public_key,
            captcha_secret_key             = :captcha_secret_key,
            telegram_bot_token             = :telegram_bot_token,
            telegram_admin_chat_id         = :telegram_admin_chat_id,
            telegram_notifications_enabled = :telegram_notifications_enabled,
            jap_api_key                    = :jap_api_key,
            jap_api_url                    = :jap_api_url,
            smm_markup                     = :smm_markup,
            sudo_api_key                   = :sudo_api_key,
            sudo_card_program              = :sudo_card_program,
            card_creation_fee              = :card_creation_fee,
            sudo_sandbox                   = :sudo_sandbox,
            announcement                   = :announcement,
            telegram_group_url             = :telegram_group_url,
            withdraw_minimum               = :withdraw_minimum,
            withdraw_fee                   = :withdraw_fee,
            paystack_dva_enabled           = :paystack_dva_enabled,
            paystack_dva_provider          = :paystack_dva_provider,
            module_virtual_numbers         = :module_virtual_numbers,
            module_smm                     = :module_smm,
            module_buy_data                = :module_buy_data,
            module_buy_airtime             = :module_buy_airtime,
            module_cable_tv                = :module_cable_tv,
            module_electricity             = :module_electricity,
            module_buy_giftcard            = :module_buy_giftcard,
            module_sell_giftcard           = :module_sell_giftcard,
            module_virtual_cards           = :module_virtual_cards,
            module_marketplace             = :module_marketplace,
            module_sell_account            = :module_sell_account,
            module_referral                = :module_referral,
            module_withdraw                = :module_withdraw,
            module_buy_logs                = :module_buy_logs
            WHERE id = 1";
    }

    $stmt = $pdo->prepare($sql);
    foreach ($settings as $key => $value) {
        $stmt->bindValue(':' . $key, $value);
    }

    if ($stmt->execute()) {
        echo json_encode(['status' => '1', 'msg' => 'Site settings updated successfully']);
    } else {
        $errorInfo = $stmt->errorInfo();
        echo json_encode(['status' => '0', 'msg' => 'Failed to update settings: ' . ($errorInfo[2] ?? 'Unknown error')]);
    }

} catch (PDOException $e) {
    error_log("Settings update error: " . $e->getMessage());
    echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
}