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

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

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized']);
    exit();
}

$config_path = dirname(__DIR__) . '/include/config.php';
require_once $config_path;
require_once dirname(__DIR__) . '/include/JAP.php';

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

$jap    = new JAP($site_data['jap_api_key'], $site_data['jap_api_url'] ?? 'https://the-owlet.com/api/v2');
$action = trim($_POST['action'] ?? '');

switch ($action) {

    // ════════════════════════════════════════════════
    // CHECK JAP BALANCE
    // ════════════════════════════════════════════════
    case 'check_balance':
        $res = $jap->getBalance();
        if (!$res['success']) {
            echo json_encode(['status' => '0', 'msg' => $res['error'] ?? 'Could not fetch balance. Check your API key.']);
            exit();
        }
        echo json_encode([
            'status'   => '1',
            'balance'  => $res['data']['balance']  ?? '0.00',
            'currency' => $res['data']['currency'] ?? 'USD',
        ]);
        break;

    // ════════════════════════════════════════════════
    // SYNC SERVICES FROM JAP
    // ════════════════════════════════════════════════
    case 'sync_services':
                $markup     = floatval($_POST['smm_markup'] ?? $site_data['smm_markup']  ?? 30);

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

        $services  = $res['data'];
        $inserted  = 0;
        $updated   = 0;

        foreach ($services as $s) {
            $jap_rate = (float)($s['rate'] ?? 0);
            $our_rate = round($jap_rate * (1 + $markup / 100), 2); // Owlet: already NGN

            $exists = $pdo->prepare("SELECT id, our_rate FROM smm_services WHERE jap_service_id = :jid LIMIT 1");
            $exists->execute(['jid' => $s['service']]);
            $row = $exists->fetch(PDO::FETCH_ASSOC);

            if ($row) {
                // Update — preserve our custom our_rate (do NOT overwrite)
                $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'    => $s['category'] ?? 'General',
                        'name'   => $s['name'],
                        'type'   => $s['type'] ?? 'Default',
                        'jrate'  => $jap_rate,
                        'min'    => $s['min'],
                        'max'    => $s['max'],
                        'refill' => (!empty($s['refill']) && $s['refill']) ? 1 : 0,
                        'cancel' => (!empty($s['cancel']) && $s['cancel']) ? 1 : 0,
                        'jid'    => $s['service'],
                    ]);
                $updated++;
            } else {
                // Insert new with auto-calculated our_rate
                $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'    => $s['service'],
                        'cat'    => $s['category'] ?? 'General',
                        'name'   => $s['name'],
                        'type'   => $s['type'] ?? 'Default',
                        'jrate'  => $jap_rate,
                        'orate'  => $our_rate,
                        'min'    => $s['min'],
                        'max'    => $s['max'],
                        'refill' => (!empty($s['refill']) && $s['refill']) ? 1 : 0,
                        'cancel' => (!empty($s['cancel']) && $s['cancel']) ? 1 : 0,
                    ]);
                $inserted++;
            }
        }

        echo json_encode([
            'status'   => '1',
            'msg'      => "{$inserted} new services added, {$updated} existing services updated. Your custom prices were preserved.",
            'inserted' => $inserted,
            'updated'  => $updated,
        ]);
        break;

    // ════════════════════════════════════════════════
    // RECALCULATE ALL RATES
    // ════════════════════════════════════════════════
    case 'recalculate_rates':
                $markup     = floatval($_POST['markup']     ?? 30);

        $pdo->prepare("UPDATE settings SET smm_markup = :m WHERE id = 1")
            ->execute(['m' => $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); // Owlet: already NGN
            $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 rates recalculated. Markup: {$markup}%",
        ]);
        break;

    // ════════════════════════════════════════════════
    // TOGGLE SERVICE STATUS
    // ════════════════════════════════════════════════
    case 'toggle_service':
        $id     = (int)($_POST['service_id'] ?? 0);
        $status = (int)($_POST['status']     ?? 0);
        if (!$id) { echo json_encode(['status' => '0', 'msg' => 'Invalid ID']); exit(); }
        $pdo->prepare("UPDATE smm_services SET status = :s WHERE id = :id")->execute(['s' => $status, 'id' => $id]);
        echo json_encode(['status' => '1', 'msg' => 'Updated']);
        break;

    // ════════════════════════════════════════════════
    // UPDATE SERVICE RATE
    // ════════════════════════════════════════════════
    case 'update_rate':
        $id   = (int)($_POST['service_id'] ?? 0);
        $rate = floatval($_POST['our_rate'] ?? 0);
        if (!$id) { echo json_encode(['status' => '0', 'msg' => 'Invalid ID']); exit(); }
        $pdo->prepare("UPDATE smm_services SET our_rate = :r WHERE id = :id")->execute(['r' => $rate, 'id' => $id]);
        echo json_encode(['status' => '1', 'msg' => 'Rate updated to ₦' . number_format($rate, 2)]);
        break;

    // ════════════════════════════════════════════════
    // EDIT SERVICE (full edit)
    // ════════════════════════════════════════════════
    case 'edit_service':
        $id     = (int)($_POST['service_id'] ?? 0);
        $name   = trim($_POST['name']     ?? '');
        $cat    = trim($_POST['category'] ?? '');
        $rate   = floatval($_POST['our_rate'] ?? 0);
        $min    = (int)($_POST['min_quantity'] ?? 10);
        $max    = (int)($_POST['max_quantity'] ?? 1000000);
        $status = (int)($_POST['status']  ?? 1);

        if (!$id || !$name) { echo json_encode(['status' => '0', 'msg' => 'Missing fields']); exit(); }

        $pdo->prepare("UPDATE smm_services SET name = :name, category = :cat, our_rate = :rate,
                        min_quantity = :min, max_quantity = :max, status = :status, updated_at = NOW()
                        WHERE id = :id")
            ->execute(['name' => $name, 'cat' => $cat, 'rate' => $rate, 'min' => $min, 'max' => $max, 'status' => $status, 'id' => $id]);

        echo json_encode(['status' => '1', 'msg' => 'Service updated successfully.']);
        break;

    // ════════════════════════════════════════════════
    // UPDATE ORDER STATUS (manual override)
    // ════════════════════════════════════════════════
    case 'update_order_status':
        $id         = (int)($_POST['order_id'] ?? 0);
        $new_status = trim($_POST['new_status'] ?? '');
        $allowed    = ['Pending','In progress','Processing','Completed','Partial','Cancelled','Refunded'];
        if (!$id || !in_array($new_status, $allowed)) {
            echo json_encode(['status' => '0', 'msg' => 'Invalid input']);
            exit();
        }
        $pdo->prepare("UPDATE smm_orders SET status = :s, updated_at = NOW() WHERE id = :id")
            ->execute(['s' => $new_status, 'id' => $id]);
        echo json_encode(['status' => '1', 'msg' => 'Order #' . $id . ' updated to ' . $new_status]);
        break;

    // ════════════════════════════════════════════════
    // SYNC SINGLE ORDER STATUS FROM JAP
    // ════════════════════════════════════════════════
    case 'sync_order':
        $id           = (int)($_POST['order_id']     ?? 0);
        $jap_order_id = (int)($_POST['jap_order_id'] ?? 0);
        if (!$id || !$jap_order_id) { echo json_encode(['status' => '0', 'msg' => 'Invalid order']); exit(); }

        $res = $jap->getOrderStatus($jap_order_id);
        if (!$res['success']) {
            echo json_encode(['status' => '0', 'msg' => $res['error'] ?? 'JAP API error']);
            exit();
        }
        $d = $res['data'];
        $pdo->prepare("UPDATE smm_orders SET status = :s, start_count = :sc, remains = :rem, jap_charge = :jc, updated_at = NOW() WHERE id = :id")
            ->execute(['s' => $d['status'] ?? 'Pending', 'sc' => $d['start_count'] ?? null, 'rem' => $d['remains'] ?? null, 'jc' => $d['charge'] ?? null, 'id' => $id]);

        echo json_encode(['status' => '1', 'order_status' => $d['status'] ?? '—', 'remains' => $d['remains'] ?? 0, 'msg' => 'Order synced.']);
        break;

    default:
        echo json_encode(['status' => '0', 'msg' => 'Unknown action']);
        break;
}
?>