<?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 || !isset($_SESSION['user_id'])) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized. Please log in.']);
    exit();
}

require_once '../../include/config.php';
require_once '../../include/JAP.php';

$jap     = new JAP($site_data['jap_api_key'], $site_data['jap_api_url'] ?? 'https://justanotherpanel.com/api/v2');
$user_id = (int)$_SESSION['user_id'];
$action  = trim($_POST['action'] ?? '');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
    exit();
}

// Load user
try {
    $u_stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id LIMIT 1");
    $u_stmt->execute(['id' => $user_id]);
    $user = $u_stmt->fetch(PDO::FETCH_ASSOC);
    if (!$user) throw new Exception('User not found');
} catch (Exception $e) {
    echo json_encode(['status' => '0', 'msg' => 'User not found.']);
    exit();
}

switch ($action) {

    // ════════════════════════════════════════════════
    // PLACE ORDER
    // ════════════════════════════════════════════════
    case 'place_order':
        $smm_service_id = filter_var($_POST['service_id'] ?? 0, FILTER_VALIDATE_INT);
        $link           = trim($_POST['link']     ?? '');
        $quantity       = filter_var($_POST['quantity'] ?? 0, FILTER_VALIDATE_INT);

        if (!$smm_service_id || !$link || !$quantity) {
            echo json_encode(['status' => '0', 'msg' => 'Please fill all fields.']);
            exit();
        }

        if (!filter_var($link, FILTER_VALIDATE_URL)) {
            echo json_encode(['status' => '0', 'msg' => 'Please enter a valid URL.']);
            exit();
        }

        // Fetch service from DB
        try {
            $svc = $pdo->prepare("SELECT * FROM smm_services WHERE id = :id AND status = 1 LIMIT 1");
            $svc->execute(['id' => $smm_service_id]);
            $service = $svc->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            echo json_encode(['status' => '0', 'msg' => 'Service not found.']);
            exit();
        }

        if (!$service) {
            echo json_encode(['status' => '0', 'msg' => 'Service not available.']);
            exit();
        }

        // Validate quantity
        if ($quantity < $service['min_quantity'] || $quantity > $service['max_quantity']) {
            echo json_encode(['status' => '0', 'msg' => 'Quantity must be between ' . number_format($service['min_quantity']) . ' and ' . number_format($service['max_quantity']) . '.']);
            exit();
        }

        // Calculate charge (our_rate is per 1000 in NGN)
        $charge = round(($quantity / 1000) * (float)$service['our_rate'], 2);

        // Check balance
        if ((float)$user['main_balance'] < $charge) {
            echo json_encode(['status' => '0', 'msg' => 'Insufficient balance. You need ₦' . number_format($charge, 2) . '.']);
            exit();
        }

        try {
            $pdo->beginTransaction();

            // Deduct balance immediately (hold)
            $pdo->prepare("UPDATE users SET main_balance = main_balance - :charge WHERE id = :uid")
                ->execute(['charge' => $charge, 'uid' => $user_id]);

            // Place order on JAP
            $jap_res = $jap->addOrder((int)$service['jap_service_id'], $link, $quantity);

            if (!$jap_res['success']) {
                $pdo->rollBack();
                echo json_encode(['status' => '0', 'msg' => 'JAP API error: ' . ($jap_res['error'] ?? 'Unknown error')]);
                exit();
            }

            $jap_order_id = (int)($jap_res['data']['order'] ?? 0);

            // Save order to DB
            $ins = $pdo->prepare("
                INSERT INTO smm_orders
                    (user_id, smm_service_id, jap_service_id, jap_order_id, link, quantity, charge, status, created_at)
                VALUES
                    (:uid, :svc_id, :jap_svc, :jap_oid, :link, :qty, :charge, 'Pending', NOW())
            ");
            $ins->execute([
                'uid'     => $user_id,
                'svc_id'  => $smm_service_id,
                'jap_svc' => $service['jap_service_id'],
                'jap_oid' => $jap_order_id,
                'link'    => $link,
                'qty'     => $quantity,
                'charge'  => $charge,
            ]);
            $db_order_id = $pdo->lastInsertId();

            // Log transaction
            $txn_ref = 'SMM_' . strtoupper(uniqid()) . '_' . time();
            $pdo->prepare("
                INSERT INTO transactions
                    (user_id, transaction_ref, payment_gateway, transaction_type, amount, currency, status, metadata, created_at)
                VALUES
                    (:uid, :ref, 'balance', 'social_boost', :amount, 'NGN', 'successful', :meta, NOW())
            ")->execute([
                'uid'    => $user_id,
                'ref'    => $txn_ref,
                'amount' => $charge,
                'meta'   => json_encode(['jap_order_id' => $jap_order_id, 'service' => $service['name'], 'link' => $link, 'quantity' => $quantity]),
            ]);

            $pdo->commit();

            echo json_encode([
                'status'   => '1',
                'msg'      => 'Order placed successfully! ₦' . number_format($charge, 2) . ' has been charged.',
                'order_id' => $db_order_id,
            ]);

        } catch (PDOException $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            error_log('smm place_order error: ' . $e->getMessage());
            echo json_encode(['status' => '0', 'msg' => 'A server error occurred. Please try again.']);
        }
        break;

    // ════════════════════════════════════════════════
    // CHECK ORDER STATUS (sync with JAP)
    // ════════════════════════════════════════════════
    case 'check_status':
        $db_order_id  = filter_var($_POST['db_order_id']  ?? 0, FILTER_VALIDATE_INT);
        $jap_order_id = filter_var($_POST['jap_order_id'] ?? 0, FILTER_VALIDATE_INT);

        // Verify ownership
        $own = $pdo->prepare("SELECT * FROM smm_orders WHERE id = :id AND user_id = :uid LIMIT 1");
        $own->execute(['id' => $db_order_id, 'uid' => $user_id]);
        $order = $own->fetch(PDO::FETCH_ASSOC);

        if (!$order) { echo json_encode(['status' => '0', 'msg' => 'Order not found.']); exit(); }

        $res = $jap->getOrderStatus($jap_order_id);

        if (!$res['success']) {
            echo json_encode(['status' => '0', 'msg' => 'Failed to fetch status: ' . ($res['error'] ?? 'Unknown error')]);
            exit();
        }

        $d = $res['data'];
        $new_status   = $d['status']      ?? $order['status'];
        $start_count  = $d['start_count'] ?? $order['start_count'];
        $remains      = $d['remains']     ?? $order['remains'];
        $jap_charge   = $d['charge']      ?? $order['jap_charge'];

        // Update DB
        $pdo->prepare("UPDATE smm_orders SET status = :status, start_count = :sc, remains = :rem, jap_charge = :jc, updated_at = NOW() WHERE id = :id")
            ->execute(['status' => $new_status, 'sc' => $start_count, 'rem' => $remains, 'jc' => $jap_charge, 'id' => $db_order_id]);

        echo json_encode([
            'status'       => '1',
            'order_status' => $new_status,
            'start_count'  => $start_count,
            'remains'      => $remains,
            'charge'       => $jap_charge,
        ]);
        break;

    // ════════════════════════════════════════════════
    // REQUEST REFILL
    // ════════════════════════════════════════════════
    case 'request_refill':
        $db_order_id  = filter_var($_POST['db_order_id']  ?? 0, FILTER_VALIDATE_INT);
        $jap_order_id = filter_var($_POST['jap_order_id'] ?? 0, FILTER_VALIDATE_INT);

        $own = $pdo->prepare("SELECT * FROM smm_orders WHERE id = :id AND user_id = :uid AND status = 'Completed' LIMIT 1");
        $own->execute(['id' => $db_order_id, 'uid' => $user_id]);
        if (!$own->fetch()) { echo json_encode(['status' => '0', 'msg' => 'Order not eligible for refill.']); exit(); }

        $res = $jap->requestRefill($jap_order_id);

        if (!$res['success']) {
            echo json_encode(['status' => '0', 'msg' => 'Refill request failed: ' . ($res['error'] ?? 'Unknown error')]);
            exit();
        }

        $refill_id = $res['data']['refill'] ?? null;
        $pdo->prepare("UPDATE smm_orders SET refill_id = :rid, updated_at = NOW() WHERE id = :id")
            ->execute(['rid' => $refill_id, 'id' => $db_order_id]);

        echo json_encode(['status' => '1', 'msg' => 'Refill requested successfully. It will be processed by JAP.']);
        break;

    // ════════════════════════════════════════════════
    // CANCEL ORDER
    // ════════════════════════════════════════════════
    case 'cancel_order':
        $db_order_id  = filter_var($_POST['db_order_id']  ?? 0, FILTER_VALIDATE_INT);
        $jap_order_id = filter_var($_POST['jap_order_id'] ?? 0, FILTER_VALIDATE_INT);

        $own = $pdo->prepare("SELECT * FROM smm_orders WHERE id = :id AND user_id = :uid LIMIT 1");
        $own->execute(['id' => $db_order_id, 'uid' => $user_id]);
        $order = $own->fetch(PDO::FETCH_ASSOC);

        if (!$order) { echo json_encode(['status' => '0', 'msg' => 'Order not found.']); exit(); }
        if (!in_array($order['status'], ['Pending', 'Processing'])) {
            echo json_encode(['status' => '0', 'msg' => 'This order cannot be cancelled (status: ' . $order['status'] . ').']);
            exit();
        }

        $res = $jap->cancelOrders([$jap_order_id]);

        if (!$res['success']) {
            echo json_encode(['status' => '0', 'msg' => 'Cancel failed: ' . ($res['error'] ?? 'Unknown error')]);
            exit();
        }

        try {
            $pdo->beginTransaction();

            // Refund undelivered portion
            $remains      = (int)($order['remains'] ?? $order['quantity']);
            $refund_amount = round(($remains / $order['quantity']) * $order['charge'], 2);

            if ($refund_amount > 0) {
                $pdo->prepare("UPDATE users SET main_balance = main_balance + :amount WHERE id = :uid")
                    ->execute(['amount' => $refund_amount, 'uid' => $user_id]);

                // Log refund transaction
                $ref = 'SMM_REFUND_' . strtoupper(uniqid());
                $pdo->prepare("INSERT INTO transactions (user_id, transaction_ref, payment_gateway, transaction_type, amount, currency, status, created_at)
                                VALUES (:uid, :ref, 'balance', 'refund', :amount, 'NGN', 'successful', NOW())")
                    ->execute(['uid' => $user_id, 'ref' => $ref, 'amount' => $refund_amount]);
            }

            // Update order status
            $pdo->prepare("UPDATE smm_orders SET status = 'Cancelled', updated_at = NOW() WHERE id = :id")
                ->execute(['id' => $db_order_id]);

            $pdo->commit();

            $msg = 'Order cancelled.';
            if ($refund_amount > 0) $msg .= ' ₦' . number_format($refund_amount, 2) . ' has been refunded to your balance.';

            echo json_encode(['status' => '1', 'msg' => $msg]);

        } catch (PDOException $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            error_log('smm cancel_order error: ' . $e->getMessage());
            echo json_encode(['status' => '0', 'msg' => 'Server error during cancellation.']);
        }
        break;

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