<?php
//Developer: core tech web design
//Whatsapp: +234 9162671360
//Telegram: @jeditech

error_reporting(0); // prevent PHP warnings from corrupting JSON output
ob_start();

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 {
    ob_clean();
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}

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

// Auth: must be logged-in admin
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized access']); exit();
}
try {
    $stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :uid");
    $stmt->bindParam(':uid', $_SESSION['user_id'], PDO::PARAM_INT);
    $stmt->execute();
    $adm = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$adm || $adm['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();
}

// Load FiveSim class
$fivesim_path = dirname(__DIR__, 2) . '/include/FiveSim.php';
if (!class_exists('FiveSim')) {
    require_once $fivesim_path;
}

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

// ════════════════════════════════════════════════════════════════
// ACTION: check_fivesim_balance
// ════════════════════════════════════════════════════════════════
if ($action === 'check_fivesim_balance') {
    $token    = trim($_POST['fivesim_api_token'] ?? '');
    $base_url = trim($_POST['fivesim_api_url']   ?? '');

    if (empty($token)) {
        // Load from DB
        $row      = $pdo->query("SELECT fivesim_api_token, fivesim_api_url FROM settings WHERE id=1")->fetch(PDO::FETCH_ASSOC);
        $token    = $row['fivesim_api_token'] ?? '';
        $base_url = $row['fivesim_api_url']   ?? '';
    }
    if (empty($base_url)) $base_url = 'https://5sim.net/v1';
    if (empty($token)) {
        echo json_encode(['status' => '0', 'msg' => 'No API token configured. Save settings first.']); exit();
    }

    $api = new FiveSim($token, $base_url);
    $r   = $api->getProfile();

    if ($r['success']) {
        $balance = $r['data']['balance'] ?? 0;
        $rating  = $r['data']['rating']  ?? 0;
        echo json_encode([
            'status'  => '1',
            'balance' => $balance,
            'rating'  => $rating,
        ]);
    } else {
        $detail = '';
        if (!empty($r['http_code'])) $detail = ' (HTTP ' . $r['http_code'] . ')';
        echo json_encode([
            'status' => '0',
            'msg'    => '5SIM API error: ' . ($r['error'] ?? 'Unknown') . $detail,
        ]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: save_fivesim_settings
// ════════════════════════════════════════════════════════════════
if ($action === 'save_fivesim_settings') {
    $api_url   = trim($_POST['fivesim_api_url']   ?? 'https://5sim.net/v1');
    $api_token = trim($_POST['fivesim_api_token'] ?? '');
    $markup    = (float)($_POST['fivesim_markup'] ?? 35);

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

    try {
        // Add columns if they don't exist yet (safe to run multiple times)
        // VARCHAR(512) to accommodate JWT Bearer tokens which can be 400-500+ chars
        $pdo->exec("ALTER TABLE settings
            ADD COLUMN IF NOT EXISTS fivesim_api_token VARCHAR(512) NOT NULL DEFAULT '',
            ADD COLUMN IF NOT EXISTS fivesim_api_url   VARCHAR(255) NOT NULL DEFAULT 'https://5sim.net/v1',
            ADD COLUMN IF NOT EXISTS fivesim_markup    FLOAT        NOT NULL DEFAULT 35");
    } catch (PDOException $e) {
        // columns already exist — try widening if needed
        try {
            $pdo->exec("ALTER TABLE settings MODIFY COLUMN fivesim_api_token VARCHAR(512) NOT NULL DEFAULT ''");
        } catch (PDOException $e2) {}
    }

    try {
        $pdo->prepare("UPDATE settings SET fivesim_api_url=:url, fivesim_api_token=:tok, fivesim_markup=:mkp WHERE id=1")
            ->execute(['url' => $api_url, 'tok' => $api_token, 'mkp' => $markup]);

        echo json_encode(['status' => '1', 'msg' => '5SIM settings saved successfully.']);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: sync_fivesim_countries
// Fetches guest/countries and upserts into fivesim_countries table
// ════════════════════════════════════════════════════════════════
if ($action === 'sync_fivesim_countries') {
    $row      = $pdo->query("SELECT fivesim_api_token, fivesim_api_url FROM settings WHERE id=1")->fetch(PDO::FETCH_ASSOC);
    $token    = $row['fivesim_api_token'] ?? '';
    $base_url = !empty($row['fivesim_api_url']) ? $row['fivesim_api_url'] : 'https://5sim.net/v1';

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

    // Ensure table exists
    $pdo->exec("CREATE TABLE IF NOT EXISTS fivesim_countries (
        id          INT AUTO_INCREMENT PRIMARY KEY,
        country_key VARCHAR(100) NOT NULL UNIQUE,
        title       VARCHAR(150) NOT NULL,
        iso         VARCHAR(10)  NOT NULL DEFAULT '',
        prefix      VARCHAR(20)  NOT NULL DEFAULT '',
        updated_at  TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $api = new FiveSim($token, $base_url);
    $r   = $api->getCountries();

    if (!$r['success']) {
        echo json_encode(['status' => '0', 'msg' => '5SIM API error: ' . ($r['error'] ?? '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 fivesim_countries (country_key, title, iso, prefix)
         VALUES (:ckey, :title, :iso, :prefix)
         ON DUPLICATE KEY UPDATE title=VALUES(title), iso=VALUES(iso), prefix=VALUES(prefix), updated_at=NOW()"
    );

    foreach ($r['data'] as $country_key => $info) {
        if (!is_array($info)) continue;
        $title  = trim($info['text_en'] ?? ucfirst((string)$country_key));
        $iso    = '';
        if (!empty($info['iso']) && is_array($info['iso'])) {
            $iso = strtolower((string)array_key_first($info['iso']));
        }
        $prefix = '';
        if (!empty($info['prefix']) && is_array($info['prefix'])) {
            $prefix = (string)array_key_first($info['prefix']);
        }

        $stmt->execute([
            'ckey'   => (string)$country_key,
            'title'  => $title ?: (string)$country_key,
            'iso'    => $iso,
            'prefix' => $prefix,
        ]);
        $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_fivesim_products
// Fetches products for every country and populates fivesim_products
// ════════════════════════════════════════════════════════════════
if ($action === 'sync_fivesim_products') {
    $row      = $pdo->query("SELECT fivesim_api_token, fivesim_api_url, fivesim_markup FROM settings WHERE id=1")->fetch(PDO::FETCH_ASSOC);
    $token    = $row['fivesim_api_token'] ?? '';
    $base_url = !empty($row['fivesim_api_url']) ? $row['fivesim_api_url'] : 'https://5sim.net/v1';
    $markup   = (float)($row['fivesim_markup'] ?? 35);

    // Also try price_settings for usd_to_ngn
    $usd_ngn  = 1600.0;
    try {
        $r2 = $pdo->query("SELECT setting_value FROM price_settings WHERE setting_key='usd_to_ngn' LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        if ($r2 && (float)$r2['setting_value'] > 0) $usd_ngn = (float)$r2['setting_value'];
    } catch (PDOException $e) {}

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

    // Get countries
    $countries = $pdo->query("SELECT country_key, title FROM fivesim_countries ORDER BY country_key ASC")->fetchAll(PDO::FETCH_ASSOC);
    if (empty($countries)) {
        echo json_encode(['status' => '0', 'msg' => 'No countries found. Sync countries first.']); exit();
    }

    // Ensure products table exists
    $pdo->exec("CREATE TABLE IF NOT EXISTS fivesim_products (
        id          INT AUTO_INCREMENT PRIMARY KEY,
        country_key VARCHAR(100) NOT NULL,
        product     VARCHAR(150) NOT NULL,
        category    VARCHAR(50)  NOT NULL DEFAULT 'activation',
        qty         INT          NOT NULL DEFAULT 0,
        cost_usd    FLOAT        NOT NULL DEFAULT 0,
        our_price   FLOAT        NOT NULL DEFAULT 0,
        synced_at   TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_country_product (country_key, product)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $api = new FiveSim($token, $base_url);

    $stmt = $pdo->prepare(
        "INSERT INTO fivesim_products (country_key, product, category, qty, cost_usd, our_price)
         VALUES (:ckey, :product, :cat, :qty, :cusd, :oprice)
         ON DUPLICATE KEY UPDATE
            category=VALUES(category), qty=VALUES(qty),
            cost_usd=VALUES(cost_usd), our_price=VALUES(our_price), synced_at=NOW()"
    );

    $total_rows     = 0;
    $countries_done = 0;
    $failed         = [];

    foreach ($countries as $country) {
        $ckey = $country['country_key'];
        $r    = $api->getProducts($ckey, 'any');

        if (!$r['success'] || !is_array($r['data'])) {
            $failed[] = $ckey;
            continue;
        }

        foreach ($r['data'] as $product => $info) {
            if (!is_array($info)) continue;
            $cat       = strtolower($info['Category'] ?? 'activation');
            if ($cat !== 'activation') continue; // skip hosting products
            $qty       = (int)($info['Qty']   ?? 0);
            $cost_usd  = (float)($info['Price'] ?? 0);
            if ($cost_usd <= 0) continue;

            $our_price = round($cost_usd * $usd_ngn * (1 + $markup / 100), 2);

            $stmt->execute([
                'ckey'   => $ckey,
                'product'=> (string)$product,
                'cat'    => $cat,
                'qty'    => $qty,
                'cusd'   => $cost_usd,
                'oprice' => $our_price,
            ]);
            $total_rows++;
        }
        $countries_done++;
    }

    $msg = "Products synced! {$countries_done}/" . count($countries) . " countries, {$total_rows} product entries.";
    if (!empty($failed)) {
        $msg .= ' Failed: ' . implode(', ', array_slice($failed, 0, 8));
    }

    echo json_encode([
        'status'          => '1',
        'msg'             => $msg,
        'countries_done'  => $countries_done,
        'total_products'  => $total_rows,
        'failed'          => $failed,
    ]);
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: sync_fivesim_all  (countries + products in one call)
// ════════════════════════════════════════════════════════════════
if ($action === 'sync_fivesim_all') {
    echo json_encode([
        'status' => '0',
        'msg'    => 'Use the dedicated "Sync Countries" and "Sync Products" buttons on the 5SIM Settings page for full sync.',
    ]);
    exit();
}

echo json_encode(['status' => '0', 'msg' => 'Unknown action: ' . htmlspecialchars($action)]);
