<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Services\MpesaService;
use Illuminate\Http\Request;
use Exception;

class PaymentController extends Controller
{
    protected $mpesaService;

    public function __construct(MpesaService $mpesaService)
    {
        $this->mpesaService = $mpesaService;
    }

    public function initiate(Request $request)
    {
        $request->validate([
            'order_id' => 'required|exists:orders,id',
            'phone_number' => 'required|string',
        ]);

        $order = Order::findOrFail($request->order_id);

        if ($order->status === 'paid') {
            return response()->json([
                'success' => false,
                'message' => 'This order has already been paid.'
            ], 400);
        }

        try {
            $result = $this->mpesaService->initiateStkPush($order, $request->phone_number);
            return response()->json($result);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 400);
        }
    }

    public function callback(Request $request)
    {
        $callbackData = $request->all();
        
        $result = $this->mpesaService->handleCallback($callbackData);

        // Safaricom expects a success status response code JSON
        return response()->json([
            'ResultCode' => 0,
            'ResultDesc' => 'Callback processed successfully'
        ]);
    }

    public function completeCod(Request $request)
    {
        $request->validate([
            'order_id' => 'required|exists:orders,id',
        ]);

        $order = Order::findOrFail($request->order_id);

        if ($order->status !== 'pending') {
            return response()->json([
                'success' => false,
                'message' => 'Order is not in pending status.'
            ], 400);
        }

        $order->update([
            'status' => 'processing',
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Order completed via Cash on Delivery.'
        ]);
    }

    public function completeManual(Request $request)
    {
        $request->validate([
            'order_id' => 'required|exists:orders,id',
            'transaction_id' => 'required|string|min:8|max:20',
        ]);

        $order = Order::findOrFail($request->order_id);

        if ($order->status !== 'pending') {
            return response()->json([
                'success' => false,
                'message' => 'Order is not in pending status.'
            ], 400);
        }

        $order->update([
            'status' => 'processing',
            'mpesa_transaction_id' => strtoupper($request->transaction_id),
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Manual payment details submitted for verification.'
        ]);
    }
}
