<?php

namespace App\Http\Controllers\Api;

use App\Models\Order;
use App\Models\Payment;
use App\Models\PaymentMethod;
use App\Services\MpesaService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class MpesaController extends ApiController
{
    public function __construct(private readonly MpesaService $mpesaService)
    {
    }

    public function stkPush(Request $request): \Illuminate\Http\JsonResponse
    {
        $request->validate([
            'order_id' => ['required', 'exists:orders,id'],
            'phone' => ['required', 'string'],
            'amount' => ['required', 'numeric', 'min:1'],
        ]);

        $order = Order::findOrFail($request->order_id);
        $this->ensureCompanyScoped($order, $this->currentCompanyId($request));

        $mpesaMethod = PaymentMethod::where('company_id', $order->company_id)
            ->where('type', 'mpesa')
            ->first();

        if (!$mpesaMethod) {
            return response()->json(['message' => 'M-Pesa payment method not configured for this company.'], 422);
        }

        // Create a pending payment
        $payment = $order->payments()->create([
            'payment_method_id' => $mpesaMethod->id,
            'amount' => $request->amount,
            'currency_code' => $order->currency_code,
            'exchange_rate' => $order->exchange_rate,
            'amount_kes' => round($request->amount * $order->exchange_rate, 4),
            'status' => 'pending',
            'notes' => 'STK Push initiated to ' . $request->phone,
        ]);

        $success = $this->mpesaService->initiateStkPush($payment, $request->phone);

        if (!$success) {
            $payment->update(['status' => 'failed', 'notes' => 'STK Push initiation failed.']);
            return response()->json(['message' => 'Failed to initiate M-Pesa STK Push. Check logs for details.'], 500);
        }

        return response()->json([
            'message' => 'STK Push initiated successfully. Please check your phone.',
            'payment_id' => $payment->id
        ]);
    }

    public function callback(Request $request): \Illuminate\Http\JsonResponse
    {
        $payload = $request->all();
        
        Log::info('Mpesa Callback Received', ['payload' => $payload]);

        $this->mpesaService->settleTransaction($payload);

        return response()->json([
            'ResultCode' => 0,
            'ResultDesc' => 'Success'
        ]);
    }
}
