<?php

namespace App\Http\Controllers;

use App\Models\Invoice;
use App\Models\Payment;
use Illuminate\Http\Request;
use Srmklive\PayPal\Services\PayPal as PayPalClient;

class PayPalController extends Controller
{
    /**
     * Begin PayPal checkout for the given invoice.
     */
    public function process(Invoice $invoice)
    {
        if (!gateway_enabled('paypal')) {
            return redirect()->route('dashboard')->with('error', 'PayPal gateway is disabled by admin.');
        }

        if ($invoice->user_id !== auth()->id()) abort(403);
        if ($invoice->isPaid()) {
            return redirect()->route('dashboard')->with('info', 'Invoice already paid.');
        }

        try {
            $provider = new PayPalClient;
            $provider->setApiCredentials(config('paypal'));
            $provider->getAccessToken();

            $response = $provider->createOrder([
                "intent" => "CAPTURE",
                "application_context" => [
                    "return_url" => route('paypal.success') . '?invoice_id=' . $invoice->id,
                    "cancel_url" => route('paypal.cancel') . '?invoice_id=' . $invoice->id,
                    "brand_name" => config('app.name'),
                    "user_action" => "PAY_NOW",
                ],
                "purchase_units" => [[
                    "reference_id" => 'INV-' . $invoice->id,
                    "description"  => 'Invoice #' . $invoice->invoice_number,
                    "amount" => [
                        "currency_code" => $invoice->currency,
                        "value" => number_format((float)$invoice->amount, 2, '.', ''),
                    ],
                ]],
            ]);

            if (isset($response['id']) && $response['id'] != null) {
                foreach ($response['links'] as $link) {
                    if ($link['rel'] === 'approve') {
                        // Save the order ID on the invoice for later capture
                        session(['paypal_order_id' => $response['id'], 'paypal_invoice_id' => $invoice->id]);
                        return redirect()->away($link['href']);
                    }
                }
            }

            return redirect()->route('paypal.cancel', ['invoice_id' => $invoice->id])
                ->with('error', 'Could not create PayPal order. ' . ($response['message'] ?? ''));
        } catch (\Throwable $e) {
            return redirect()->back()->with('error', 'PayPal error: ' . $e->getMessage());
        }
    }

    /**
     * Capture the order after the user approves on PayPal.
     */
    public function success(Request $request)
    {
        if (!gateway_enabled('paypal')) {
            return redirect()->route('dashboard')->with('error', 'PayPal gateway is disabled by admin.');
        }

        $invoiceId = $request->get('invoice_id') ?: session('paypal_invoice_id');
        $token = $request->get('token') ?: session('paypal_order_id');

        if (!$invoiceId) {
            return redirect()->route('dashboard')->with('error', 'Missing invoice context.');
        }
        $invoice = Invoice::findOrFail($invoiceId);
        if ($invoice->user_id !== auth()->id()) abort(403);

        try {
            $provider = new PayPalClient;
            $provider->setApiCredentials(config('paypal'));
            $provider->getAccessToken();

            $response = $provider->capturePaymentOrder($token);

            if (isset($response['status']) && $response['status'] === 'COMPLETED') {
                $payerEmail = $response['payer']['email_address'] ?? null;
                $txnId = $response['purchase_units'][0]['payments']['captures'][0]['id'] ?? $token;

                Payment::create([
                    'user_id'        => $invoice->user_id,
                    'invoice_id'     => $invoice->id,
                    'amount'         => $invoice->amount,
                    'currency'       => $invoice->currency,
                    'gateway'        => 'paypal',
                    'transaction_id' => $txnId,
                    'payer_email'    => $payerEmail,
                    'status'         => 'completed',
                    'response'       => $response,
                ]);

                $invoice->update([
                    'status'         => 'paid',
                    'paid_at'        => now(),
                    'payment_method' => 'paypal',
                    'transaction_id' => $txnId,
                ]);

                // Add quota if linked to a package and user is reseller
                if ($invoice->package_id && $invoice->user && $invoice->user->isReseller()) {
                    $invoice->user->increment('blogs_quota', $invoice->package->blogs_count);
                }

                return redirect()->route('dashboard')->with('success', 'Payment successful! Invoice #' . $invoice->invoice_number . ' is paid.');
            }

            return redirect()->route('dashboard')->with('error', 'Payment was not completed.');
        } catch (\Throwable $e) {
            return redirect()->route('dashboard')->with('error', 'PayPal capture error: ' . $e->getMessage());
        }
    }

    public function cancel(Request $request)
    {
        return redirect()->route('dashboard')->with('error', 'Payment cancelled.');
    }
}
