<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ApiClient;
use App\Models\WalletRecharge;
use App\Mail\RechargeInvoiceMail;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\DB;

class WidgetWalletController extends Controller
{
    /**
     * Get the wallet info and recent transaction history for the authenticated client.
     */
    public function getWalletInfo(Request $request)
    {
        $client = $request->attributes->get('api_client');

        if (!$client) {
            return response()->json([
                'success' => false,
                'message' => 'Client not authenticated.'
            ], 401);
        }

        $recharges = $client->recharges()
            ->where('status', 'completed')
            ->orderBy('id', 'desc')
            ->take(10)
            ->get();

        return response()->json([
            'success' => true,
            'client' => [
                'name' => $client->name,
                'email' => $client->email,
                'wallet_balance' => number_format($client->wallet_balance, 2, '.', ''),
                'pan_charge' => number_format($client->pan_charge, 2, '.', ''),
                'aadhaar_otp_charge' => number_format($client->aadhaar_otp_charge, 2, '.', ''),
                'aadhaar_submit_charge' => number_format($client->aadhaar_submit_charge, 2, '.', ''),
                'aadhaar_basic_charge' => number_format($client->aadhaar_basic_charge, 2, '.', ''),
                'aadhaar_pan_link_charge' => number_format($client->aadhaar_pan_link_charge, 2, '.', ''),
                'gst_charge' => number_format($client->gst_charge, 2, '.', ''),
                'bank_charge' => number_format($client->bank_charge, 2, '.', ''),
            ],
            'recharges' => $recharges->map(function ($recharge) {
                return [
                    'id' => $recharge->id,
                    'amount' => number_format($recharge->amount, 2),
                    'previous_balance' => number_format($recharge->previous_balance, 2),
                    'new_balance' => number_format($recharge->new_balance, 2),
                    'date' => $recharge->created_at->format('M d, Y H:i'),
                ];
            })
        ]);
    }

    /**
     * Initiate a Zoho checkout recharge.
     */
    public function initiateRecharge(Request $request)
    {
        $client = $request->attributes->get('api_client');

        if (!$client) {
            return response()->json([
                'success' => false,
                'message' => 'Client not authenticated.'
            ], 401);
        }

        $validated = $request->validate([
            'amount' => 'required|numeric|min:1',
        ]);

        $amount = $validated['amount'];

        // Create a pending wallet recharge log
        $recharge = WalletRecharge::create([
            'api_client_id' => $client->id,
            'amount' => $amount,
            'previous_balance' => $client->wallet_balance,
            'new_balance' => $client->wallet_balance, // Will be updated on successful payment
            'status' => 'pending',
            'payment_id' => null,
        ]);

        // Check if real Zoho credentials are set in .env
        $zohoClientId = env('ZOHO_PAYMENTS_CLIENT_ID');
        $zohoClientSecret = env('ZOHO_PAYMENTS_CLIENT_SECRET');

        if (!empty($zohoClientId) && !empty($zohoClientSecret)) {
            // Integration with real Zoho Checkout API goes here
            // e.g. call Zoho Checkout HPP (Hosted Payment Page) endpoint, generate checkout url
            $redirectUrl = $this->generateRealZohoUrl($recharge);
        } else {
            // Fallback to local Mock Zoho Checkout Gateway
            $redirectUrl = route('zoho.mock-checkout', ['recharge_id' => $recharge->id]);
        }

        return response()->json([
            'success' => true,
            'redirect_url' => $redirectUrl,
        ]);
    }

    /**
     * Display the Mock Zoho Checkout page.
     */
    public function mockCheckout($recharge_id)
    {
        $recharge = WalletRecharge::with('apiClient')->findOrFail($recharge_id);

        if ($recharge->status !== 'pending') {
            return view('admin.zoho_mock_result', [
                'recharge' => $recharge,
                'status' => $recharge->status,
                'message' => 'This transaction has already been processed.'
            ]);
        }

        return view('admin.zoho_mock_checkout', compact('recharge'));
    }

    /**
     * Complete the Mock Zoho Checkout transaction.
     */
    public function completeMockCheckout(Request $request, $recharge_id)
    {
        $recharge = WalletRecharge::with('apiClient')->findOrFail($recharge_id);

        if ($recharge->status !== 'pending') {
            return redirect()->route('zoho.mock-checkout', ['recharge_id' => $recharge->id]);
        }

        $status = $request->input('status'); // 'completed' or 'failed'

        if ($status === 'completed') {
            DB::transaction(function () use ($recharge) {
                $client = ApiClient::lockForUpdate()->findOrFail($recharge->api_client_id);
                $prevBalance = $client->wallet_balance;
                
                // Credit the client
                $client->increment('wallet_balance', $recharge->amount);
                $newBalance = $client->wallet_balance;

                // Update recharge record
                $recharge->update([
                    'previous_balance' => $prevBalance,
                    'new_balance' => $newBalance,
                    'status' => 'completed',
                    'payment_id' => 'ZOHO_MOCK_' . Str::random(12),
                ]);

                // Send invoice mail if email exists
                if ($client->email) {
                    try {
                        Mail::to($client->email)->send(new RechargeInvoiceMail($recharge));
                    } catch (\Exception $e) {
                        // Log mail failure but do not crash the transaction
                        \Log::error("Failed to send invoice mail during mock checkout: " . $e->getMessage());
                    }
                }
            });

            return view('admin.zoho_mock_result', [
                'recharge' => $recharge,
                'status' => 'completed',
                'message' => 'Payment successful! Wallet balance credited.'
            ]);
        } else {
            $recharge->update([
                'status' => 'failed'
            ]);

            return view('admin.zoho_mock_result', [
                'recharge' => $recharge,
                'status' => 'failed',
                'message' => 'Payment failed or cancelled by user.'
            ]);
        }
    }

    /**
     * Real Zoho Checkout webhook / success callback placeholder.
     */
    public function zohoCallback(Request $request)
    {
        // Handle Zoho redirect callback
        return response()->json(['message' => 'Real Zoho Callback reached. Place integration verification logic here.']);
    }

    /**
     * Simulate creating a real Zoho Checkout link.
     */
    protected function generateRealZohoUrl(WalletRecharge $recharge)
    {
        // Place real Zoho integration credentials & token exchanges here.
        // Returns checkout page URL.
        return 'https://checkout.zoho.com/documentverification/recharge?id=' . $recharge->id;
    }
}
