<?php
// app/Http/Controllers/Api/MobileMoneyController.php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\MobileMoneyService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;

class MobileMoneyController extends Controller
{
    protected $mobileMoneyService;

    public function __construct(MobileMoneyService $mobileMoneyService)
    {
        $this->mobileMoneyService = $mobileMoneyService;
    }

    /**
     * Initiate mobile money payment
     */
    public function initiatePayment(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'mobile_number' => 'required|string|max:15',
            'amount' => 'required|numeric|min:1',
            'customer_name' => 'required|string|max:255',
            'email' => 'required|email',
            'company_id' => 'required|integer',
            'loan_id' => 'nullable|integer', // For loan payments
            'description' => 'nullable|string'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        $paymentResult = $this->mobileMoneyService->initiatePayment($request->all());

        if (!$paymentResult['success']) {
            return response()->json([
                'success' => false,
                'message' => 'Payment initiation failed',
                'error' => $paymentResult['error']
            ], 400);
        }

        // Handle pending transactions with polling
        if ($paymentResult['status'] === 'Pending') {
            $pollingResult = $this->mobileMoneyService->pollTransactionStatus(
                $paymentResult['transaction_id'],
                $request->company_id
            );

            if ($pollingResult['success']) {
                // Payment successful - record in database
                $this->recordSuccessfulPayment($request->all(), $paymentResult, $pollingResult);
                
                return response()->json([
                    'success' => true,
                    'message' => 'Payment completed successfully',
                    'transaction_id' => $paymentResult['transaction_id'],
                    'reference_number' => $paymentResult['external_id'],
                    'amount' => $paymentResult['amount']
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Payment failed or timed out',
                    'status' => $pollingResult['status'],
                    'error' => $pollingResult['error'] ?? 'Payment processing failed'
                ], 400);
            }
        }

        // Handle immediate success or failure
        if ($paymentResult['status'] === 'Successful') {
            $this->recordSuccessfulPayment($request->all(), $paymentResult);
            
            return response()->json([
                'success' => true,
                'message' => 'Payment completed successfully',
                'transaction_id' => $paymentResult['transaction_id'],
                'reference_number' => $paymentResult['external_id'],
                'amount' => $paymentResult['amount']
            ]);
        } else {
            return response()->json([
                'success' => false,
                'message' => 'Payment failed',
                'status' => $paymentResult['status'],
                'error' => $paymentResult['message'] ?? 'Payment failed'
            ], 400);
        }
    }

    /**
     * Check transaction status
     */
    public function checkStatus(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'transaction_id' => 'required|string',
            'company_id' => 'required|integer'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        $statusResult = $this->mobileMoneyService->checkTransactionStatus(
            $request->transaction_id,
            $request->company_id
        );

        return response()->json($statusResult);
    }

    /**
     * Record successful payment in database
     */
    private function recordSuccessfulPayment($paymentData, $paymentResult, $pollingResult = null)
    {
        try {
            // Implement your payment recording logic here
            // This should insert into your payments table
            
            $paymentRecord = [
                'amount' => $paymentResult['amount'],
                'mobile_number' => $paymentData['mobile_number'],
                'customer_name' => $paymentData['customer_name'],
                'transaction_id' => $paymentResult['transaction_id'],
                'external_id' => $paymentResult['external_id'],
                'payment_method' => 'Mobile Money',
                'payment_currency' => 'ZMW',
                'company_id' => $paymentData['company_id'],
                'loan_id' => $paymentData['loan_id'] ?? null,
                'description' => $paymentData['description'] ?? null,
                'payment_date' => now()->format('Y-m-d'),
                'payment_time' => now()->format('H:i:s'),
                'payment_week' => now()->weekOfYear,
                'payment_year' => now()->year,
                'status' => 'successful',
                'created_at' => now(),
                'updated_at' => now()
            ];

            // Insert into your payments table
            // DB::table('payments')->insert($paymentRecord);
            
            \Log::info('Payment recorded successfully', $paymentRecord);

        } catch (\Exception $e) {
            \Log::error('Failed to record payment in database', [
                'error' => $e->getMessage(),
                'payment_data' => $paymentData,
                'payment_result' => $paymentResult
            ]);
        }
    }
}