<?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_row = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$admin_row || $admin_row['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 SMSMan class - try both path styles
$smsman_path = dirname(__DIR__, 2) . '/include/SMSMan.php';
if (!file_exists($smsman_path)) {
    $smsman_path = dirname(__DIR__) . '/include/SMSMan.php';
}
if (!file_exists($smsman_path)) {
    echo json_encode(['status' => '0', 'msg' => 'SMSMan.php not found. Upload include/SMSMan.php first.']);
    exit();
}
if (!class_exists('SMSMan')) {
    require_once $smsman_path;
}

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

// ════════════════════════════════════════════════════════════════
// ACTION: check_smsman_balance
// ════════════════════════════════════════════════════════════════
if ($action === 'check_smsman_balance') {
    $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']   ?? '';
    }
    if (empty($base_url)) $base_url = 'https://api.sms-man.com/control';
    if (empty($token)) {
        echo json_encode(['status' => '0', 'msg' => 'No API token. 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'] ?? 'Check your token.')]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: save_smsman_settings
// ════════════════════════════════════════════════════════════════
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: sync_smsman_countries
// ════════════════════════════════════════════════════════════════
if ($action === 'sync_smsman_countries') {
    $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 = !empty($row['smsman_api_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" 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_smsman_apps
// ════════════════════════════════════════════════════════════════
if ($action === 'sync_smsman_apps') {
    $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 = !empty($row['smsman_api_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" 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 $key => $a) {
        $aid  = (int)($a['id']    ?? $key ?? 0);
        $name = trim($a['title']  ?? $a['name'] ?? '');  // API returns 'title' not '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_smsman_all
// ════════════════════════════════════════════════════════════════
if ($action === 'sync_smsman_all') {
    $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 = !empty($row['smsman_api_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" 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 to fetch countries'];
    }

    // 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 $key => $a) {
            $aid  = (int)($a['id']   ?? $key ?? 0);
            $name = trim($a['title'] ?? $a['name'] ?? '');  // API returns 'title' not '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 to fetch services'];
    }

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

// ════════════════════════════════════════════════════════════════
// ACTION: sync_smsman_prices
// Fetches getLimits() for every country and populates smsman_prices
// This is the key sync that links countries → services with prices
// ════════════════════════════════════════════════════════════════
if ($action === 'sync_smsman_prices') {
    $row      = $pdo->query("SELECT smsman_api_token, smsman_api_url, smsman_markup, usd_to_ngn FROM settings WHERE id=1")->fetch(PDO::FETCH_ASSOC);
    $token    = $row['smsman_api_token'] ?? '';
    $base_url = !empty($row['smsman_api_url']) ? $row['smsman_api_url'] : 'https://api.sms-man.com/control';
    $markup   = (float)($row['smsman_markup'] ?? 30);
    $usd_ngn  = (float)($row['usd_to_ngn']   ?? 1600);

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

    // Get all countries from DB
    $countries = $pdo->query("SELECT id, title FROM smsman_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 all app names/codes from DB for lookup
    $app_lookup = [];
    $apps = $pdo->query("SELECT id, name, code FROM smsman_applications")->fetchAll(PDO::FETCH_ASSOC);
    foreach ($apps as $app) {
        $app_lookup[(int)$app['id']] = ['name' => $app['name'], 'code' => $app['code']];
    }

    $smsman = new SMSMan($token, $base_url);

    $stmt = $pdo->prepare("INSERT INTO smsman_prices
        (country_id, application_id, app_name, app_code, cost_usd, our_price, available)
        VALUES (:cid, :aid, :aname, :acode, :cusd, :oprice, :avail)
        ON DUPLICATE KEY UPDATE
            app_name=VALUES(app_name), app_code=VALUES(app_code),
            cost_usd=VALUES(cost_usd), our_price=VALUES(our_price),
            available=VALUES(available), synced_at=NOW()");

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

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

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

        foreach ($r['data'] as $app_id => $item) {
            $aid       = (int)($item['application_id'] ?? $app_id);
            $cost_usd  = (float)($item['cost']    ?? 0);
            $available = (int)($item['numbers']   ?? 0);
            if ($aid <= 0 || $cost_usd <= 0) continue;

            $our_price = round($cost_usd * $usd_ngn * (1 + $markup / 100), 2);
            // Use API name if available, fall back to DB lookup
            $app_name  = $item['application'] ?? ($app_lookup[$aid]['name'] ?? '');
            $app_code  = $app_lookup[$aid]['code'] ?? '';

            $stmt->execute([
                'cid'    => $cid,
                'aid'    => $aid,
                'aname'  => $app_name,
                'acode'  => $app_code,
                'cusd'   => $cost_usd,
                'oprice' => $our_price,
                'avail'  => $available,
            ]);
            $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, 5));
    }

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

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