<?php

namespace App\Services;

use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Core\ProductionEnvironment;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
use PayPalCheckoutSdk\Orders\OrdersGetRequest;

class PayPalService
{
    protected PayPalHttpClient $client;
    protected string $currency;

    public function __construct()
    {
        $clientId     = config('services.paypal.client_id');
        $clientSecret = config('services.paypal.client_secret');
        $this->currency = config('services.paypal.currency', 'USD');

        $environment = config('services.paypal.mode') === 'live'
            ? new ProductionEnvironment($clientId, $clientSecret)
            : new SandboxEnvironment($clientId, $clientSecret);

        $this->client = new PayPalHttpClient($environment);
    }

    public function createOrder(float $amount, ?string $referenceId = null, ?string $returnUrl = null, ?string $cancelUrl = null)
    {
        $request = new OrdersCreateRequest();
        $request->prefer('return=representation');
        $request->body = [
            'intent' => 'CAPTURE',
            'purchase_units' => [[
                'reference_id' => $referenceId ?: uniqid('ref_', true),
                'amount' => [
                    'currency_code' => $this->currency,
                    'value' => number_format($amount, 2, '.', ''),
                ],
            ]],
            'application_context' => [
                'brand_name'   => config('app.name'),
                'landing_page' => 'NO_PREFERENCE',
                'user_action'  => 'PAY_NOW',
                'return_url'   => $returnUrl,
                'cancel_url'   => $cancelUrl,
            ],
        ];

        $response = $this->client->execute($request);
        return $response->result;
    }

    public function getOrder(string $orderId)
    {
        $request = new OrdersGetRequest($orderId);
        $response = $this->client->execute($request);
        return $response->result;
    }

    public function captureOrder(string $orderId)
    {
        $request = new OrdersCaptureRequest($orderId);
        $request->prefer('return=representation');

        // IMPORTANT for paypalhttp 1.0:
        // Must be a string or array. The API expects an empty JSON OBJECT, not an array.
        $request->headers['Content-Type'] = 'application/json';
        $request->body = '{}'; // ✅ use '{}' (string). Do NOT use [].

        // (Optional) idempotency
        $request->headers['PayPal-Request-Id'] = 'cap_'.($orderId);

        $response = $this->client->execute($request);
        return $response->result;
    }
}
