<?php
/**
 * API Handler for Fingpay AEPS
 * 
 * This file handles all form submissions and processes AEPS transactions
 * Credentials are hardcoded as per requirement
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

require_once 'FingpayAEPS.php';

// Load API configuration
$configFile = __DIR__ . '/api_config.php';
if (!file_exists($configFile)) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Configuration file not found'
    ]);
    exit;
}

$config = require $configFile;

// Load credentials from configuration
$credentials = $config['credentials'] ?? [];
$MERCHANT_ID = $credentials['merchant_id'] ?? $credentials['super_merchant_id'] ?? '1143';
$TERMINAL_ID = $credentials['merchant_id'] ?? $credentials['super_merchant_id'] ?? '1143'; // Using merchant_id as terminal_id
$DEFAULT_DEVICE_IMEI = $credentials['default_device_imei'] ?? '8982848';
$USERNAME = $credentials['username'] ?? 'Paydeer';
$PASSWORD = $credentials['password'] ?? 'Paydeer@2025';
$SECRET_KEY = $credentials['secret_key'] ?? '';
$IP_ADDRESS = $credentials['ip_address'] ?? '82.29.165.61';

// Path to the public certificate file
$certPath = $config['certificate_path'] ?? (__DIR__ . '/../fingpay_public_production.txt');

// Get JSON input
$input = file_get_contents('php://input');
$request = json_decode($input, true);

if (!$request || !isset($request['type']) || !isset($request['data'])) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid request format'
    ]);
    exit;
}

$type = $request['type'];
$data = $request['data'];

try {
    // Initialize the Fingpay AEPS client
    $fingpay = new FingpayAEPS($certPath, 30);
    
    // Generate unique transaction reference
    $transactionRef = 'TXN' . time() . rand(1000, 9999);
    
    // Get device IMEI or use default
    $deviceIMEI = isset($data['deviceIMEI']) && !empty($data['deviceIMEI']) 
        ? $data['deviceIMEI'] 
        : $DEFAULT_DEVICE_IMEI;
    
    $response = null;
    
    switch ($type) {
        case 'withdrawal':
            // Validate required fields
            if (empty($data['aadhaarNumber']) || empty($data['amount']) || 
                empty($data['customerName']) || empty($data['bankCode'])) {
                throw new Exception('All required fields must be filled');
            }
            
            // Prepare biometric data if provided
            $additionalParams = [];
            if (!empty($data['biometricData'])) {
                $additionalParams['biometricData'] = $data['biometricData'];
                $additionalParams['biometricType'] = $data['biometricType'] ?? 'FINGERPRINT';
            }
            
            $response = $fingpay->cashWithdrawal(
                $MERCHANT_ID,
                $TERMINAL_ID,
                $data['aadhaarNumber'],
                floatval($data['amount']),
                $data['customerName'],
                $transactionRef,
                $data['bankCode'],
                $deviceIMEI,
                $additionalParams
            );
            break;
            
        case 'balance':
            // Validate required fields
            if (empty($data['aadhaarNumber']) || empty($data['bankCode'])) {
                throw new Exception('Aadhaar number and bank code are required');
            }
            
            // Prepare biometric data if provided
            $additionalParams = [];
            if (!empty($data['biometricData'])) {
                $additionalParams['biometricData'] = $data['biometricData'];
                $additionalParams['biometricType'] = $data['biometricType'] ?? 'FINGERPRINT';
            }
            
            $response = $fingpay->balanceInquiry(
                $MERCHANT_ID,
                $TERMINAL_ID,
                $data['aadhaarNumber'],
                $data['bankCode'],
                $transactionRef,
                $deviceIMEI,
                $additionalParams
            );
            break;
            
        case 'statement':
            // Validate required fields
            if (empty($data['aadhaarNumber']) || empty($data['bankCode'])) {
                throw new Exception('Aadhaar number and bank code are required');
            }
            
            // Prepare biometric data if provided
            $additionalParams = [];
            if (!empty($data['biometricData'])) {
                $additionalParams['biometricData'] = $data['biometricData'];
                $additionalParams['biometricType'] = $data['biometricType'] ?? 'FINGERPRINT';
            }
            
            $response = $fingpay->miniStatement(
                $MERCHANT_ID,
                $TERMINAL_ID,
                $data['aadhaarNumber'],
                $data['bankCode'],
                $transactionRef,
                $deviceIMEI,
                $additionalParams
            );
            break;
            
        case 'deposit':
            // Validate required fields
            if (empty($data['aadhaarNumber']) || empty($data['amount']) || 
                empty($data['customerName']) || empty($data['bankCode'])) {
                throw new Exception('All required fields must be filled');
            }
            
            // Prepare biometric data if provided
            $additionalParams = [];
            if (!empty($data['biometricData'])) {
                $additionalParams['biometricData'] = $data['biometricData'];
                $additionalParams['biometricType'] = $data['biometricType'] ?? 'FINGERPRINT';
            }
            
            $response = $fingpay->cashDeposit(
                $MERCHANT_ID,
                $TERMINAL_ID,
                $data['aadhaarNumber'],
                floatval($data['amount']),
                $data['customerName'],
                $transactionRef,
                $data['bankCode'],
                $deviceIMEI,
                $additionalParams
            );
            break;
            
        case 'user_onboard':
        case 'user_verify':
            // User Onboarding API is NOT available in Fingpay AEPS API documentation
            // This API was implemented based on assumption but does not exist
            throw new Exception('User Onboarding API is not available in Fingpay AEPS API documentation. This feature is not supported.');
            
        case 'merchant_onboard':
            // Validate required fields
            if (empty($data['merchantName']) || empty($data['merchantMobile']) || 
                empty($data['merchantEmail'])) {
                throw new Exception('Merchant name, mobile, and email are required');
            }
            
            $response = $fingpay->merchantOnboard($data, $deviceIMEI);
            break;
            
        case 'merchant_status':
            // Validate required fields
            if (empty($data['merchantId'])) {
                throw new Exception('Merchant ID is required');
            }
            
            $response = $fingpay->merchantStatus($data['merchantId'], $deviceIMEI);
            break;
            
        case 'ekyc_verify':
            // Validate required fields
            if (empty($data['aadhaarNumber'])) {
                throw new Exception('Aadhaar number is required for EKYC verification');
            }
            
            $otp = $data['otp'] ?? '';
            $additionalParams = [];
            if (!empty($data['biometricData'])) {
                $additionalParams['biometricData'] = $data['biometricData'];
                $additionalParams['biometricType'] = $data['biometricType'] ?? 'FINGERPRINT';
            }
            
            $response = $fingpay->ekycVerify($data['aadhaarNumber'], $otp, $deviceIMEI, $additionalParams);
            break;
            
        case 'ekyc_status':
            // Validate required fields
            if (empty($data['referenceId'])) {
                throw new Exception('Reference ID is required');
            }
            
            $response = $fingpay->ekycStatus($data['referenceId'], $deviceIMEI);
            break;
            
        case 'ekyc_enroll':
            // Validate required fields
            if (empty($data['aadhaarNumber']) || empty($data['mobileNumber'])) {
                throw new Exception('Aadhaar number and mobile number are required');
            }
            
            $response = $fingpay->ekycEnroll($data, $deviceIMEI);
            break;
            
        default:
            throw new Exception('Invalid transaction type');
    }
    
    // Return response
    if (isset($response['status']) && $response['status'] === 'error') {
        echo json_encode([
            'status' => 'error',
            'message' => $response['message'] ?? 'Transaction failed',
            'data' => $response
        ]);
    } else {
        echo json_encode([
            'status' => 'success',
            'message' => 'Transaction processed successfully',
            'data' => $response,
            'transactionRef' => $transactionRef
        ]);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage(),
        'error' => $e->getTraceAsString()
    ]);
}

