<?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 SmsBus class
$smsbus_path = dirname(__DIR__, 2) . '/include/SmsBus.php';
if (!class_exists('SmsBus')) {
    require_once $smsbus_path;
}

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

// ════════════════════════════════════════════════════════════════
// ACTION: check_smsbus_balance
// ════════════════════════════════════════════════════════════════
if ($action === 'check_smsbus_balance') {
    $token    = trim($_POST['smsbus_api_token'] ?? '');
    $base_url = trim($_POST['smsbus_api_url']   ?? '');

    if (empty($token)) {
        // Load from DB
        try {
            $row      = $pdo->query("SELECT smsbus_api_token, smsbus_api_url FROM settings WHERE id=1")->fetch(PDO::FETCH_ASSOC);
            $token    = trim($row['smsbus_api_token'] ?? '');
            $base_url = trim($row['smsbus_api_url']   ?? '');
        } catch (PDOException $e) {}
    }
    if (empty($base_url)) $base_url = 'https://sms-bus.com/api/control';
    if (empty($token)) {
        echo json_encode(['status' => '0', 'msg' => 'No API token configured. Save settings first.']); exit();
    }

    $api = new SmsBus($token, $base_url);
    $r   = $api->getBalance();

    if ($r['success'] && isset($r['data']['balance'])) {
        $balance = (float)$r['data']['balance'];
        echo json_encode([
            'status'  => '1',
            'balance' => $balance,
        ]);
    } else {
        $detail = '';
        if (!empty($r['code'])) $detail = ' (code ' . $r['code'] . ')';
        echo json_encode([
            'status' => '0',
            'msg'    => 'SMS-Bus API error: ' . ($r['error'] ?? 'Unknown') . $detail,
        ]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: save_smsbus_settings
// ════════════════════════════════════════════════════════════════
if ($action === 'save_smsbus_settings') {
    $api_url   = trim($_POST['smsbus_api_url']   ?? 'https://sms-bus.com/api/control');
    $api_token = trim($_POST['smsbus_api_token'] ?? '');
    $markup    = (float)($_POST['smsbus_markup'] ?? 35);

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

    try {
        $pdo->exec("ALTER TABLE settings
            ADD COLUMN IF NOT EXISTS smsbus_api_token VARCHAR(255) NOT NULL DEFAULT '',
            ADD COLUMN IF NOT EXISTS smsbus_api_url   VARCHAR(255) NOT NULL DEFAULT 'https://sms-bus.com/api/control',
            ADD COLUMN IF NOT EXISTS smsbus_markup    FLOAT        NOT NULL DEFAULT 35");
    } catch (PDOException $e) {}

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

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

// ════════════════════════════════════════════════════════════════
// ACTION: sync_smsbus_countries
// Fetches list/countries and upserts into smsbus_countries table
// ════════════════════════════════════════════════════════════════
if ($action === 'sync_smsbus_countries') {
    $row      = $pdo->query("SELECT smsbus_api_token, smsbus_api_url FROM settings WHERE id=1")->fetch(PDO::FETCH_ASSOC);
    $token    = trim($row['smsbus_api_token'] ?? '');
    $base_url = !empty($row['smsbus_api_url']) ? $row['smsbus_api_url'] : 'https://sms-bus.com/api/control';

    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 smsbus_countries (
        id         INT PRIMARY KEY,
        title      VARCHAR(150) NOT NULL,
        code       VARCHAR(10)  NOT NULL DEFAULT '',
        updated_at TIMESTAMP    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

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

    if (!$r['success']) {
        echo json_encode(['status' => '0', 'msg' => 'SMS-Bus 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 smsbus_countries (id, title, code)
         VALUES (:id, :title, :code)
         ON DUPLICATE KEY UPDATE title=VALUES(title), code=VALUES(code), updated_at=NOW()"
    );

    foreach ($r['data'] as $item) {
        if (!is_array($item) || empty($item['id'])) continue;
        $stmt->execute([
            'id'    => (int)$item['id'],
            'title' => (string)($item['title'] ?? ''),
            'code'  => strtolower((string)($item['code'] ?? '')),
        ]);
        $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_smsbus_projects
// Fetches list/projects and upserts into smsbus_projects table
// ════════════════════════════════════════════════════════════════
if ($action === 'sync_smsbus_projects') {
    $row      = $pdo->query("SELECT smsbus_api_token, smsbus_api_url FROM settings WHERE id=1")->fetch(PDO::FETCH_ASSOC);
    $token    = trim($row['smsbus_api_token'] ?? '');
    $base_url = !empty($row['smsbus_api_url']) ? $row['smsbus_api_url'] : 'https://sms-bus.com/api/control';

    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 smsbus_projects (
        id         INT PRIMARY KEY,
        title      VARCHAR(150) NOT NULL,
        code       VARCHAR(50)  NOT NULL DEFAULT '',
        updated_at TIMESTAMP    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $api = new SmsBus($token, $base_url);
    $r   = $api->getProjects();

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

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

    foreach ($r['data'] as $item) {
        if (!is_array($item) || empty($item['id'])) continue;
        $stmt->execute([
            'id'    => (int)$item['id'],
            'title' => (string)($item['title'] ?? ''),
            'code'  => strtolower((string)($item['code'] ?? '')),
        ]);
        $rc = $stmt->rowCount();
        if ($rc == 1) $inserted++;
        elseif ($rc >= 2) $updated++;
    }

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

// ════════════════════════════════════════════════════════════════
// ACTION: sync_smsbus_prices
// For each country, calls getPrices(country_id), stores in smsbus_prices
// ════════════════════════════════════════════════════════════════
if ($action === 'sync_smsbus_prices') {
    $row      = $pdo->query("SELECT smsbus_api_token, smsbus_api_url, smsbus_markup FROM settings WHERE id=1")->fetch(PDO::FETCH_ASSOC);
    $token    = trim($row['smsbus_api_token'] ?? '');
    $base_url = !empty($row['smsbus_api_url']) ? $row['smsbus_api_url'] : 'https://sms-bus.com/api/control';
    $markup   = (float)($row['smsbus_markup'] ?? 35);

    $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();
    }

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

    // Get projects for title/code lookup
    $projects_map = [];
    try {
        $proj_rows = $pdo->query("SELECT id, title, code FROM smsbus_projects")->fetchAll(PDO::FETCH_ASSOC);
        foreach ($proj_rows as $p) $projects_map[(int)$p['id']] = $p;
    } catch (PDOException $e) {}

    // Ensure prices table exists
    $pdo->exec("CREATE TABLE IF NOT EXISTS smsbus_prices (
        id            INT AUTO_INCREMENT PRIMARY KEY,
        country_id    INT          NOT NULL,
        project_id    INT          NOT NULL,
        project_title VARCHAR(150) NOT NULL DEFAULT '',
        project_code  VARCHAR(50)  NOT NULL DEFAULT '',
        cost_usd      FLOAT        NOT NULL DEFAULT 0,
        our_price     FLOAT        NOT NULL DEFAULT 0,
        total_count   INT          NOT NULL DEFAULT 0,
        synced_at     TIMESTAMP    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_cp (country_id, project_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

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

    $stmt = $pdo->prepare(
        "INSERT INTO smsbus_prices (country_id, project_id, project_title, project_code, cost_usd, our_price, total_count)
         VALUES (:cid, :pid, :ptitle, :pcode, :cusd, :oprice, :cnt)
         ON DUPLICATE KEY UPDATE
            project_title=VALUES(project_title), project_code=VALUES(project_code),
            cost_usd=VALUES(cost_usd), our_price=VALUES(our_price),
            total_count=VALUES(total_count), synced_at=NOW()"
    );

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

    foreach ($countries as $country) {
        $cid = (int)$country['id'];
        $r   = $api->getPrices($cid);

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

        foreach ($r['data'] as $item) {
            if (!is_array($item)) continue;
            $pid       = (int)($item['project_id'] ?? 0);
            $cost_usd  = (float)($item['cost']        ?? 0);
            $cnt       = (int)($item['total_count']   ?? 0);
            if ($pid <= 0 || $cost_usd <= 0) continue;

            $p_info     = $projects_map[$pid] ?? null;
            $p_title    = $p_info ? $p_info['title'] : '';
            $p_code     = $p_info ? $p_info['code']  : '';
            $our_price  = round($cost_usd * $usd_ngn * (1 + $markup / 100), 2);

            $stmt->execute([
                'cid'    => $cid,
                'pid'    => $pid,
                'ptitle' => $p_title,
                'pcode'  => $p_code,
                'cusd'   => $cost_usd,
                'oprice' => $our_price,
                'cnt'    => $cnt,
            ]);
            $total_rows++;
        }
        $countries_done++;
    }

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

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

// ════════════════════════════════════════════════════════════════
// ACTION: sync_smsbus_all  (countries + projects + prices)
// ════════════════════════════════════════════════════════════════
if ($action === 'sync_smsbus_all') {
    echo json_encode([
        'status' => '0',
        'msg'    => 'Use the dedicated sync buttons on the SMS-Bus Settings page for a controlled sync.',
    ]);
    exit();
}

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