<?php
/**
 * Vodafone Cash Payment Gateway Integration
 * AUTO TESTER - Payment Processing System
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Load configuration
require_once __DIR__ . '/../../config.php';

// Vodafone Cash API Configuration
define('VODAFONE_API_URL', 'https://api.vodafone.com.eg/cash/v1');
define('VODAFONE_MERCHANT_ID', VODAFONE_MERCHANT_ID ?? 'demo_merchant');
define('VODAFONE_API_KEY', VODAFONE_API_KEY ?? 'demo_api_key');
define('VODAFONE_WEBHOOK_SECRET', VODAFONE_WEBHOOK_SECRET ?? 'demo_webhook_secret');

class VodafoneCashGateway {
    private $merchantId;
    private $apiKey;
    private $apiUrl;
    
    public function __construct() {
        $this->merchantId = VODAFONE_MERCHANT_ID;
        $this->apiKey = VODAFONE_API_KEY;
        $this->apiUrl = VODAFONE_API_URL;
    }
    
    /**
     * Initiate payment
     */
    public function initiatePayment($amount, $phoneNumber, $orderId) {
        $payload = [
            'merchant_id' => $this->merchantId,
            'amount' => $amount,
            'currency' => 'EGP',
            'customer_phone' => $phoneNumber,
            'order_id' => $orderId,
            'description' => 'AUTO TESTER Inspection Payment',
            'callback_url' => BASE_URL . '/core/api/payments/vodafone_callback.php',
            'webhook_url' => BASE_URL . '/core/api/payments/vodafone_webhook.php'
        ];
        
        $response = $this->makeRequest('/payments/initiate', $payload);
        
        if ($response['success']) {
            return [
                'success' => true,
                'payment_id' => $response['data']['payment_id'],
                'session_id' => $response['data']['session_id'],
                'expires_at' => $response['data']['expires_at']
            ];
        } else {
            return [
                'success' => false,
                'message' => $response['message'] ?? 'Failed to initiate payment'
            ];
        }
    }
    
    /**
     * Send OTP to customer
     */
    public function sendOTP($phoneNumber, $sessionId) {
        $payload = [
            'merchant_id' => $this->merchantId,
            'phone_number' => $phoneNumber,
            'session_id' => $sessionId,
            'otp_type' => 'payment'
        ];
        
        $response = $this->makeRequest('/otp/send', $payload);
        
        return [
            'success' => $response['success'],
            'otp_id' => $response['data']['otp_id'] ?? null,
            'message' => $response['message'] ?? '',
            'expires_in' => $response['data']['expires_in'] ?? 300
        ];
    }
    
    /**
     * Verify OTP and process payment
     */
    public function verifyAndPay($sessionId, $otp, $pin) {
        $payload = [
            'merchant_id' => $this->merchantId,
            'session_id' => $sessionId,
            'otp_code' => $otp,
            'customer_pin' => $pin
        ];
        
        $response = $this->makeRequest('/payments/confirm', $payload);
        
        if ($response['success']) {
            return [
                'success' => true,
                'status' => $response['data']['status'],
                'transaction_id' => $response['data']['transaction_id'],
                'paid_amount' => $response['data']['paid_amount'],
                'processed_at' => $response['data']['processed_at']
            ];
        } else {
            return [
                'success' => false,
                'message' => $response['message'] ?? 'Payment verification failed'
            ];
        }
    }
    
    /**
     * Check payment status
     */
    public function checkPaymentStatus($paymentId) {
        $payload = [
            'merchant_id' => $this->merchantId,
            'payment_id' => $paymentId
        ];
        
        $response = $this->makeRequest('/payments/status', $payload);
        
        return [
            'success' => true,
            'status' => $response['data']['status'],
            'paid_amount' => $response['data']['paid_amount'],
            'transaction_id' => $response['data']['transaction_id'],
            'paid_at' => $response['data']['paid_at']
        ];
    }
    
    /**
     * Refund payment
     */
    public function refundPayment($paymentId, $amount, $reason) {
        $payload = [
            'merchant_id' => $this->merchantId,
            'payment_id' => $paymentId,
            'amount' => $amount,
            'reason' => $reason
        ];
        
        $response = $this->makeRequest('/payments/refund', $payload);
        
        return [
            'success' => $response['success'],
            'refund_id' => $response['data']['refund_id'] ?? null,
            'message' => $response['message'] ?? ''
        ];
    }
    
    /**
     * Make API request
     */
    private function makeRequest($endpoint, $payload) {
        $url = $this->apiUrl . $endpoint;
        
        $headers = [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->apiKey,
            'X-Merchant-ID: ' . $this->merchantId
        ];
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => true
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            return ['success' => false, 'message' => 'Curl error: ' . $error];
        }
        
        $data = json_decode($response, true);
        
        if ($httpCode !== 200) {
            return ['success' => false, 'message' => $data['message'] ?? 'API request failed'];
        }
        
        return $data;
    }
    
    /**
     * Validate webhook signature
     */
    public function validateWebhookSignature($payload, $signature) {
        $expectedSignature = hash_hmac('sha256', $payload, VODAFONE_WEBHOOK_SECRET);
        return hash_equals($expectedSignature, $signature);
    }
    
    /**
     * Validate phone number for Vodafone
     */
    public function validatePhoneNumber($phoneNumber) {
        // Vodafone numbers start with 010
        return preg_match('/^010[0-9]{8}$/', $phoneNumber);
    }
}

// Handle API requests
try {
    $gateway = new VodafoneCashGateway();
    $action = $_GET['action'] ?? '';
    
    switch ($action) {
        case 'initiate_payment':
            handleInitiatePayment($gateway);
            break;
            
        case 'send_otp':
            handleSendOTP($gateway);
            break;
            
        case 'verify_payment':
            handleVerifyPayment($gateway);
            break;
            
        case 'check_status':
            handleCheckStatus($gateway);
            break;
            
        case 'refund':
            handleRefund($gateway);
            break;
            
        default:
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'Invalid action'
            ]);
    }
    
} catch (Exception $e) {
    error_log("Vodafone Cash API Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Internal server error'
    ]);
}

/**
 * Handle initiate payment request
 */
function handleInitiatePayment($gateway) {
    $input = json_decode(file_get_contents('php://input'), true);
    
    // Validate required fields
    $required = ['amount', 'phone_number', 'order_id'];
    foreach ($required as $field) {
        if (empty($input[$field])) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => "Missing required field: {$field}"
            ]);
            return;
        }
    }
    
    // Validate amount
    $amount = floatval($input['amount']);
    if ($amount <= 0 || $amount > 50000) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Invalid amount'
        ]);
        return;
    }
    
    // Validate phone number
    if (!$gateway->validatePhoneNumber($input['phone_number'])) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Invalid Vodafone phone number. Must start with 010'
        ]);
        return;
    }
    
    // Initiate payment
    $result = $gateway->initiatePayment(
        $amount,
        $input['phone_number'],
        $input['order_id']
    );
    
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
}

/**
 * Handle send OTP request
 */
function handleSendOTP($gateway) {
    $input = json_decode(file_get_contents('php://input'), true);
    
    // Validate required fields
    $required = ['phone_number', 'session_id'];
    foreach ($required as $field) {
        if (empty($input[$field])) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => "Missing required field: {$field}"
            ]);
            return;
        }
    }
    
    // Validate phone number
    if (!$gateway->validatePhoneNumber($input['phone_number'])) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Invalid Vodafone phone number'
        ]);
        return;
    }
    
    $result = $gateway->sendOTP($input['phone_number'], $input['session_id']);
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
}

/**
 * Handle verify payment request
 */
function handleVerifyPayment($gateway) {
    $input = json_decode(file_get_contents('php://input'), true);
    
    // Validate required fields
    $required = ['session_id', 'otp', 'pin'];
    foreach ($required as $field) {
        if (empty($input[$field])) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => "Missing required field: {$field}"
            ]);
            return;
        }
    }
    
    // Validate OTP format
    if (!preg_match('/^[0-9]{6}$/', $input['otp'])) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Invalid OTP format. Must be 6 digits'
        ]);
        return;
    }
    
    // Validate PIN format
    if (!preg_match('/^[0-9]{4}$/', $input['pin'])) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Invalid PIN format. Must be 4 digits'
        ]);
        return;
    }
    
    $result = $gateway->verifyAndPay(
        $input['session_id'],
        $input['otp'],
        $input['pin']
    );
    
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
}

/**
 * Handle check status request
 */
function handleCheckStatus($gateway) {
    $paymentId = $_GET['payment_id'] ?? '';
    
    if (empty($paymentId)) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Payment ID is required'
        ]);
        return;
    }
    
    $result = $gateway->checkPaymentStatus($paymentId);
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
}

/**
 * Handle refund request
 */
function handleRefund($gateway) {
    $input = json_decode(file_get_contents('php://input'), true);
    
    // Validate required fields
    $required = ['payment_id', 'amount', 'reason'];
    foreach ($required as $field) {
        if (empty($input[$field])) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => "Missing required field: {$field}"
            ]);
            return;
        }
    }
    
    $result = $gateway->refundPayment(
        $input['payment_id'],
        floatval($input['amount']),
        $input['reason']
    );
    
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
}
?>
