<?php

namespace App\Services;

use App\Models\Order;
use App\Models\Setting;
use Stripe\StripeClient;

class StripeService
{
    protected ?StripeClient $stripe = null;

    protected function getSecret(): ?string
    {
        return Setting::get('stripe_secret') ?: config('services.stripe.secret');
    }

    protected function getKey(): ?string
    {
        return Setting::get('stripe_key') ?: config('services.stripe.key');
    }

    protected function getWebhookSecret(): ?string
    {
        return Setting::get('stripe_webhook_secret') ?: config('services.stripe.webhook_secret');
    }

    public function __construct()
    {
        $key = $this->getSecret();
        if ($key) {
            $this->stripe = new StripeClient($key);
        }
    }

    public function isConfigured(): bool
    {
        return $this->stripe !== null && ! empty($this->getSecret());
    }

    public function createPaymentIntent(Order $order): ?array
    {
        if (! $this->isConfigured()) {
            return null;
        }

        $amount = (int) round($order->total * 100); // Stripe uses cents

        if ($amount < 50) { // Stripe minimum
            return null;
        }

        $intent = $this->stripe->paymentIntents->create([
            'amount' => $amount,
            'currency' => 'eur',
            'metadata' => [
                'order_id' => $order->id,
                'order_number' => $order->number,
            ],
            'automatic_payment_methods' => ['enabled' => true],
        ]);

        $order->update([
            'stripe_payment_intent_id' => $intent->id,
            'stripe_payment_status' => $intent->status,
        ]);

        return [
            'client_secret' => $intent->client_secret,
            'publishable_key' => $this->getKey(),
        ];
    }

    public function retrievePaymentIntent(string $intentId)
    {
        if (! $this->isConfigured()) {
            return null;
        }

        return $this->stripe->paymentIntents->retrieve($intentId);
    }

    public function constructWebhookEvent(string $payload, string $signature)
    {
        $secret = $this->getWebhookSecret();
        if (! $secret) {
            return null;
        }

        return \Stripe\Webhook::constructEvent(
            $payload,
            $signature,
            $secret
        );
    }
}
