<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\BayarcashService;

class PaymentController extends Controller
{
    protected $bayarcashService;

    public function __construct(BayarcashService $bayarcashService)
    {
        $this->bayarcashService = $bayarcashService;
    }

    public function success(Request $request)
    {
        $paymentIntentId = $request->get('payment_intent_id');

        if ($paymentIntentId) {
            $paymentDetails = $this->bayarcashService->verifyPayment($paymentIntentId);

            return view('payment.success', compact('paymentDetails'));
        }

        return redirect()->route('home')->with('error', 'Payment verification failed');
    }

    public function callback(Request $request)
    {
        // Log incoming webhook request
        \Log::info('Webhook Request Received', [
            'ip' => $request->ip(),
            'method' => $request->method(),
            'content_type' => $request->header('Content-Type'),
        ]);

        $payload = $request->all();

        // Validate required fields
        if (empty($payload['order_number'])) {
            \Log::warning('Webhook Missing Order Number', $payload);
            return response()->json([
                'status' => 'error',
                'message' => 'Missing order_number'
            ], 400);
        }

        $result = $this->bayarcashService->handleCallback($payload);

        if ($result) {
            return response()->json([
                'status' => 'success',
                'message' => 'Webhook processed successfully'
            ], 200);
        }

        return response()->json([
            'status' => 'error',
            'message' => 'Webhook processing failed'
        ], 400);
    }
}
