<?php
/**
 * InstaPay 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';

// InstaPay API Configuration
define('INSTAPAY_API_URL', 'https://api.instapay.com.eg/v1');
define('INSTAPAY_MERCHANT_ID', INSTAPAY_MERCHANT_ID ?? 'demo_merchant');
define('INSTAPAY_API_KEY', INSTAPAY_API_KEY ?? 'demo_api_key');
define('INSTAPAY_WEBHOOK_SECRET', INSTAPAY_WEBHOOK_SECRET ?? 'demo_webhook_secret');

class InstaPayGateway {
    private $merchantId;
    private $apiKey;
    private $apiUrl;
    
    public function __construct() {
        $this->merchantId = INSTAPAY_MERCHANT_ID;
        $this->apiKey = INSTAPAY_API_KEY;
        $this->apiUrl = INSTAPAY_API_URL;
    }
    
    /**
     * Create payment request
     */
    public function createPayment($amount, $phoneNumber, $customerName, $orderId) {
        $payload = [
            'merchant_id' => $this->merchantId,
            'amount' => $amount,
            'currency' => 'EGP',
            'customer_phone' => $phoneNumber,
            'customer_name' => $customerName,
            'order_id' => $orderId,
            'description' => 'AUTO TESTER Inspection Payment',
            'callback_url' => BASE_URL . '/core/api/payments/instapay_callback.php',
            'webhook_url' => BASE_URL . '/core/api/payments/instapay_webhook.php',
            'expiry_minutes' => 15
        ];
        
        $response = $this->makeRequest('/payments/create', $payload);
        
        if ($response['success']) {
            return [
                'success' => true,
                'payment_id' => $response['data']['payment_id'],
                'qr_code' => $response['data']['qr_code'],
                'payment_url' => $response['data']['payment_url'],
                'expires_at' => $response['data']['expires_at']
            ];
        } else {
            return [
                'success' => false,
                'message' => $response['message'] ?? 'Failed to create payment'
            ];
        }
    }
    
    /**
     * 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, INSTAPAY_WEBHOOK_SECRET);
        return hash_equals($expectedSignature, $signature);
    }
}

// Handle API requests
try {
    $gateway = new InstaPayGateway();
    $action = $_GET['action'] ?? '';
    
    switch ($action) {
        case 'create_payment':
            handleCreatePayment($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("InstaPay API Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Internal server error'
    ]);
}

/**
 * Handle create payment request
 */
function handleCreatePayment($gateway) {
    $input = json_decode(file_get_contents('php://input'), true);
    
    // Validate required fields
    $required = ['amount', 'phone_number', 'customer_name', '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 (!preg_match('/^01[0-9]{9}$/', $input['phone_number'])) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Invalid phone number format'
        ]);
        return;
    }
    
    // Create payment
    $result = $gateway->createPayment(
        $amount,
        $input['phone_number'],
        $input['customer_name'],
        $input['order_id']
    );
    
    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);
}
?>
