<?php

namespace App\Http\Controllers;

use App\Enums\BookingStatus;
use App\Enums\PaymentStatus;
use App\Models\Booking;
use App\Services\HyperpayService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class HyperpayController extends Controller
{
    protected $hyperpayService;

    public function __construct(HyperpayService $hyperpayService)
    {
        $this->hyperpayService = $hyperpayService;
    }

    public function showPaymentForm($checkoutId = null)
    {
        if (!$checkoutId && env('HYPER_PAY_MODE') == 'test') {
            $checkout = $this->hyperpayService->checkout('10.00', 'test@example.com', 1);
            Log::info("payment reply", $checkout);

            // if (!isset($checkout['id'])) {
            //     return back()->withErrors(['error' => 'Failed to create checkout. Please try again.']);
            // }

            $checkoutId = $checkout['id'];
        }
        return view('hyperpay.form', compact('checkoutId'));
    }

    public function paymentStatus(Request $request)
    {
        $checkoutId = $request->get('id');
        if (!$checkoutId) {
            return redirect()->route('payment.status-page', ['status' => __('messages.invalid_request_no_checkout_id'), 'success' => false]);
        }
        Log::info("payment checkout id", ['checkoutId' => $checkoutId, ...$request->all()]);
        $paymentStatus = $this->hyperpayService->getPaymentStatus($checkoutId);
        Log::info("payment status received", $paymentStatus);


        if (!isset($paymentStatus['id'])) {
            return redirect()->route('payment.status-page', ['status' => __('messages.payment_status_could_not_be_retrieved'), 'success' => false]);
        }

        // Regex for successful payment codes
        $successPattern = '/^(000\.000\.|000\.100\.1|000\.[23])/';
        if (isset($paymentStatus['result']['code']) && preg_match($successPattern, $paymentStatus['result']['code'])) {
            $bookingId = $paymentStatus['merchantTransactionId'];
            $booking = Booking::find($bookingId);
            $paid_amount = $paymentStatus['amount'];
            if ($booking && $booking->payment_status !== PaymentStatus::PAID) {
                $booking->update([
                    'payment_method' => $paymentStatus['paymentBrand'] ?? 'hyperpay',
                    'payment_status' => PaymentStatus::PAID,
                    'status' => BookingStatus::PAID,
                ]);
                $booking->forceFill([
                    'payment_id' => $paymentStatus['id'],
                    'payment_response' => json_encode($paymentStatus),
                ])->save();

                // Notify providers
                $booking->load('items.serviceProvider', 'user');
                foreach ($booking->items as $item) {
                    try {
                        $provider = $item->serviceProvider;
                        if ($provider) {
                            $provider->notify(new \App\Notifications\NewOrderProviderNotification($item, $booking->user));
                        }
                    } catch (\Exception $e) {
                        Log::error("New Order Provider notification error", ["error" => $e->getMessage()]);
                    }
                }
            }
            return redirect()->route('payment.status-page', ['status' => __('messages.payment_successful'), 'success' => true]);
        } else {
            $statusMessage = $paymentStatus['result']['description'] ?? __('messages.payment_failed');
            return redirect()->route('payment.status-page', ['status' => $statusMessage, 'success' => false]);
        }
    }

    public function paymentStatusPage(Request $request)
    {
        $status = $request->get('status', __('messages.no_status_provided'));
        return view('hyperpay.status', compact('status'));
    }
}
