<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}
require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/api/LocalLubanApi.php';

// Price multiplier to earn profit (User requested 1.5 - 2x)
const PRICE_MULTIPLIER = 1.8;

$pdo = db();

// Ensure apikey is loaded
$db_apikey = null;
try {
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'lubansms_apikey'");
    $stmt->execute();
    $db_apikey = $stmt->fetchColumn();
    
    // Fallback if direct match fails
    if (!$db_apikey) {
        $settings = $pdo->query("SELECT setting_key, setting_value FROM settings")->fetchAll(PDO::FETCH_KEY_PAIR);
        foreach ($settings as $k => $v) {
            if (strpos($k, 'lubansms_apikey') !== false) {
                $db_apikey = trim($v);
                break;
            }
        }
    }
} catch (Exception $e) {}

$api = new LubanSMS($db_apikey);

$action = $_GET['action'] ?? '';

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

// Basic Auth check
if (!isset($_SESSION['user_id']) && $action !== 'login') {
    echo json_encode(['code' => 401, 'msg' => '未登录或登录已过期']);
    exit;
}

try {
    switch ($action) {
        case 'get_balance':
            $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
            $stmt->execute([$_SESSION['user_id']]);
            $balance = $stmt->fetchColumn();
            echo json_encode(['code' => 0, 'balance' => number_format((float)$balance, 2)]);
            break;

        case 'get_countries':
            $res = $api->getCountries();
            echo json_encode(['code' => 0, 'data' => $res['msg'] ?? $res['data'] ?? []], JSON_UNESCAPED_UNICODE);
            break;

        case 'get_services':
            $country = $_GET['country'] ?? '';
            $service = $_GET['service'] ?? '';
            $res = $api->getServices($country, $service);
            if ($res && (int)($res['code'] ?? -1) === 0) {
                $data = $res['msg'] ?? $res['data'] ?? [];
                if (!is_array($data)) $data = [];
                foreach ($data as &$item) {
                    if (isset($item['cost'])) {
                        $item['cost'] = round((float)$item['cost'] * PRICE_MULTIPLIER, 2);
                    }
                }
                echo json_encode(['code' => 0, 'data' => $data], JSON_UNESCAPED_UNICODE);
            } else {
                echo json_encode($res ?: ['code' => 500, 'msg' => '获取项目列表 失败'], JSON_UNESCAPED_UNICODE);
            }
            break;

        case 'get_number':
            $service_id = $_GET['service_id'] ?? '';
            $country_name = $_GET['country_name'] ?? '未知国家';
            $service_name = $_GET['service_name'] ?? '未知项目';
            $price = round((float)($_GET["price"] ?? 0), 2);
            
            $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
            $stmt->execute([$_SESSION['user_id']]);
            $balance = (float)$stmt->fetchColumn();
            if ($balance < $price) {
                echo json_encode(['code' => 400, 'msg' => '余额不足，请先充值']);
                break;
            }

            $res = $api->getNumber($service_id);
            if ($res && (int)($res['code'] ?? -1) === 0) {
                $pdo->beginTransaction();
                try {
                    $stmt = $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
                    $stmt->execute([$price, $_SESSION['user_id']]);
                    $stmt = $pdo->prepare("INSERT INTO sms_orders (user_id, request_id, number, service_name, country_name, cost, status, expire_at) VALUES (?, ?, ?, ?, ?, ?, 'pending', DATE_ADD(NOW(), INTERVAL 10 MINUTE))");
                    $stmt->execute([$_SESSION['user_id'], $res['request_id'], $res['number'], $service_name, $country_name, $price]);
                    $pdo->commit();
                    echo json_encode($res, JSON_UNESCAPED_UNICODE);
                } catch (Exception $e) {
                    $pdo->rollBack();
                    echo json_encode(['code' => 500, 'msg' => '数据库事务错误'], JSON_UNESCAPED_UNICODE);
                }
            } else {
                echo json_encode($res ?: ['code' => 500, 'msg' => 'API获取号码失败'], JSON_UNESCAPED_UNICODE);
            }
            break;
            
        case 'release_number':
            $request_id = $_GET['request_id'] ?? '';
            $stmt = $pdo->prepare("SELECT * FROM sms_orders WHERE request_id = ? AND user_id = ? AND status = 'pending'");
            $stmt->execute([$request_id, $_SESSION['user_id']]);
            $order = $stmt->fetch();
            if ($order) {
                $api->releaseNumber($request_id);
                $pdo->beginTransaction();
                try {
                    $stmt = $pdo->prepare("UPDATE sms_orders SET status = 'canceled' WHERE request_id = ?");
                    $stmt->execute([$request_id]);
                    $stmt = $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
                    $stmt->execute([$order['cost'], $_SESSION['user_id']]);
                    $pdo->commit();
                    echo json_encode(['code' => 0, 'msg' => '成功']);
                } catch (Exception $e) {
                    $pdo->rollBack();
                    echo json_encode(['code' => 500, 'msg' => '错误']);
                }
            } else {
                echo json_encode(['code' => 400, 'msg' => '无效操作']);
            }
            break;

        case 'check_sms':
            $request_id = $_GET['request_id'] ?? '';
            $res = $api->getSms($request_id);
            if ($res && (int)($res['code'] ?? -1) === 0 && (string)($res['msg'] ?? '') === 'success') {
                $stmt = $pdo->prepare("UPDATE sms_orders SET sms_content = ?, status = 'received' WHERE request_id = ?");
                $stmt->execute([$res['sms_code'], $request_id]);
            }
            echo json_encode($res ?: ['code' => 500, 'msg' => 'API Error'], JSON_UNESCAPED_UNICODE);
            break;

        case "get_active_orders":
            $stmt = $pdo->prepare("SELECT * FROM sms_orders WHERE user_id = ? AND status IN ('pending', 'received') ORDER BY created_at DESC");
            $stmt->execute([$_SESSION["user_id"]]);
            echo json_encode(["code" => 0, "data" => $stmt->fetchAll(PDO::FETCH_ASSOC)], JSON_UNESCAPED_UNICODE);
            break;

        default:
            echo json_encode(['code' => 404, 'msg' => '未知请求']);
            break;
    }
} catch (Exception $e) {
    echo json_encode(['code' => 500, 'msg' => $e->getMessage()]);
}