<?php

namespace App\Http\Controllers;

use App\Services\FiuuCloudEcrService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class FiuuEcrController extends Controller
{
    protected FiuuCloudEcrService $fiuuService;

    public function __construct(FiuuCloudEcrService $fiuuService)
    {
        $this->fiuuService = $fiuuService;
    }

    /**
     * Display the sale page
     */
    public function index()
    {
        $isAuthenticated = Session::has('fiuu_access_token');
        $terminals = [];
        $ewalletChannels = [];

        if ($isAuthenticated) {
            $this->fiuuService->setAccessToken(Session::get('fiuu_access_token'));
            
            // Get terminals
            $terminalResult = $this->fiuuService->getTerminals();
            if ($terminalResult['success']) {
                $terminals = $terminalResult['data']['data'] ?? [];
            }

            // Get e-wallet channels
            $channelResult = $this->fiuuService->getEwalletChannels('MYR');
            if ($channelResult['success']) {
                $ewalletChannels = $channelResult['data']['data'] ?? [];
            }
        }

        return view('fiuu-ecr.index', [
            'isAuthenticated' => $isAuthenticated,
            'terminals' => $terminals,
            'ewalletChannels' => $ewalletChannels,
            'posId' => $this->fiuuService->getPosId(),
            'merchantId' => $this->fiuuService->getMerchantId(),
            'deviceId' => $this->fiuuService->getDeviceId(),
        ]);
    }

    /**
     * Authenticate with Fiuu cloudECR
     */
    public function login(Request $request)
    {
        $result = $this->fiuuService->authenticate();

        if ($result['success']) {
            Session::put('fiuu_access_token', $result['data']['access']['token']);
            Session::put('fiuu_refresh_token', $result['data']['refresh']['token']);
            Session::put('fiuu_token_expires', $result['data']['access']['expiresAt']);

            return response()->json([
                'success' => true,
                'message' => 'Authentication successful',
                'expiresAt' => $result['data']['access']['expiresAt'],
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => 'Authentication failed',
            'error' => $result['error'] ?? 'Unknown error',
        ], 401);
    }

    /**
     * Logout and clear session
     */
    public function logout()
    {
        Session::forget(['fiuu_access_token', 'fiuu_refresh_token', 'fiuu_token_expires']);

        return response()->json([
            'success' => true,
            'message' => 'Logged out successfully',
        ]);
    }

    /**
     * Refresh the access token
     */
    public function refreshToken()
    {
        if (!Session::has('fiuu_refresh_token')) {
            return response()->json([
                'success' => false,
                'message' => 'No refresh token available',
            ], 401);
        }

        $this->fiuuService->setRefreshToken(Session::get('fiuu_refresh_token'));
        $result = $this->fiuuService->refreshAccessToken();

        if ($result['success']) {
            Session::put('fiuu_access_token', $result['data']['access']['token']);
            Session::put('fiuu_refresh_token', $result['data']['refresh']['token']);
            Session::put('fiuu_token_expires', $result['data']['access']['expiresAt']);

            return response()->json([
                'success' => true,
                'message' => 'Token refreshed successfully',
                'expiresAt' => $result['data']['access']['expiresAt'],
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => 'Token refresh failed',
            'error' => $result['error'] ?? 'Unknown error',
        ], 401);
    }

    /**
     * Get list of terminals
     */
    public function getTerminals()
    {
        if (!Session::has('fiuu_access_token')) {
            return response()->json([
                'success' => false,
                'message' => 'Not authenticated',
            ], 401);
        }

        $this->fiuuService->setAccessToken(Session::get('fiuu_access_token'));
        $result = $this->fiuuService->getTerminals();

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

    /**
     * Get e-wallet channels
     */
    public function getEwalletChannels(Request $request)
    {
        if (!Session::has('fiuu_access_token')) {
            return response()->json([
                'success' => false,
                'message' => 'Not authenticated',
            ], 401);
        }

        $currency = $request->input('currency', 'MYR');
        
        $this->fiuuService->setAccessToken(Session::get('fiuu_access_token'));
        $result = $this->fiuuService->getEwalletChannels($currency);

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

    /**
     * Process a sale transaction
     */
    public function sale(Request $request)
    {
        $request->validate([
            'amount' => 'required|numeric|min:0.01',
            'payment_method' => 'required|in:bankCard,qrCustScan,qrMerchScan',
            'payment_channel' => 'required_if:payment_method,qrCustScan',
            'reference_label' => 'nullable|string|max:10',
            'note' => 'nullable|string|max:128',
            'print_count' => 'nullable|integer|min:0|max:2',
        ]);

        if (!Session::has('fiuu_access_token')) {
            return response()->json([
                'success' => false,
                'message' => 'Not authenticated. Please login first.',
            ], 401);
        }

        $this->fiuuService->setAccessToken(Session::get('fiuu_access_token'));

        $result = $this->fiuuService->sale(
            $request->input('amount'),
            $request->input('payment_method'),
            $request->input('payment_channel'),
            $request->input('reference_label'),
            $request->input('note'),
            $request->input('print_count', 2)
        );

        if ($result['success']) {
            $responseData = $result['data'];
            
            // Store last transaction for void capability
            if (isset($responseData['transData']['transId'])) {
                Session::put('last_trans_id', $responseData['transData']['transId']);
                Session::put('last_inv_no', $responseData['transData']['invNo'] ?? null);
            }

            return response()->json([
                'success' => true,
                'message' => $this->getStatusMessage($responseData['statusCode'] ?? '11'),
                'data' => $responseData,
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => 'Transaction failed',
            'error' => $result['error'] ?? 'Unknown error',
        ], 400);
    }

    /**
     * Process a void transaction
     */
    public function void(Request $request)
    {
        $request->validate([
            'trans_id' => 'required|string',
            'inv_no' => 'nullable|string',
        ]);

        if (!Session::has('fiuu_access_token')) {
            return response()->json([
                'success' => false,
                'message' => 'Not authenticated. Please login first.',
            ], 401);
        }

        $this->fiuuService->setAccessToken(Session::get('fiuu_access_token'));

        $result = $this->fiuuService->void(
            $request->input('trans_id'),
            $request->input('inv_no')
        );

        if ($result['success']) {
            return response()->json([
                'success' => true,
                'message' => $this->getStatusMessage($result['data']['statusCode'] ?? '11'),
                'data' => $result['data'],
            ]);
        }

        return response()->json([
            'success' => false,
            'message' => 'Void failed',
            'error' => $result['error'] ?? 'Unknown error',
        ], 400);
    }

    /**
     * Get last transaction
     */
    public function getLast()
    {
        if (!Session::has('fiuu_access_token')) {
            return response()->json([
                'success' => false,
                'message' => 'Not authenticated. Please login first.',
            ], 401);
        }

        $this->fiuuService->setAccessToken(Session::get('fiuu_access_token'));
        $result = $this->fiuuService->getLast();

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

    /**
     * Generate signature for testing
     */
    public function generateSignature(Request $request)
    {
        $payload = $request->input('payload', []);
        
        if (empty($payload)) {
            return response()->json([
                'success' => false,
                'message' => 'Payload is required',
            ], 400);
        }

        $signature = $this->fiuuService->generateSignature($payload);

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

    /**
     * Get status message from status code
     */
    protected function getStatusMessage(string $statusCode): string
    {
        return match ($statusCode) {
            '00' => 'Transaction Successful',
            '11' => 'Transaction Failed',
            '22' => 'Transaction Pending',
            default => 'Unknown Status',
        };
    }
}
