<?php
/**
 * PhonePe API Endpoint
 * Main API for Flutter app to communicate with PhonePe
 */

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

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

require_once 'phonepe_order.php';
require_once '../config/database.php';

class PhonePeAPI {
    private $orderService;
    private $db;
    
    public function __construct() {
        $this->orderService = new PhonePeOrder();
        $this->db = new Database();
    }
    
    /**
     * Handle API requests
     */
    public function handleRequest() {
        $method = $_SERVER['REQUEST_METHOD'];
        $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $path = str_replace('/astro_admin/api/phonepe_api.php', '', $path);
        
        try {
            switch ($method) {
                case 'POST':
                    if ($path === '/create-order') {
                        $this->createOrder();
                    } elseif ($path === '/check-status') {
                        $this->checkStatus();
                    } else {
                        $this->sendError('Endpoint not found', 404);
                    }
                    break;
                    
                case 'GET':
                    if ($path === '/health') {
                        $this->healthCheck();
                    } else {
                        $this->sendError('Endpoint not found', 404);
                    }
                    break;
                    
                default:
                    $this->sendError('Method not allowed', 405);
            }
        } catch (Exception $e) {
            $this->sendError('Internal server error: ' . $e->getMessage(), 500);
        }
    }
    
    /**
     * Create order endpoint
     */
    private function createOrder() {
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!$input) {
            $this->sendError('Invalid JSON input', 400);
            return;
        }
        
        // Validate required fields
        $required = ['amount', 'userId', 'orderId'];
        foreach ($required as $field) {
            if (!isset($input[$field])) {
                $this->sendError("Missing required field: $field", 400);
                return;
            }
        }
        
        // Prepare order data
        $orderData = [
            'orderId' => $input['orderId'],
            'amount' => (float)$input['amount'],
            'userId' => $input['userId'],
            'mobileNumber' => $input['mobileNumber'] ?? '',
            'email' => $input['email'] ?? ''
        ];
        
        // Create order in PhonePe
        $result = $this->orderService->createOrder($orderData);
        
        if ($result['success']) {
            // Save order to database
            $this->saveOrderToDatabase($orderData, $result);
            
            $this->sendSuccess([
                'orderId' => $result['orderId'],
                'token' => $result['token'],
                'amount' => $result['amount'],
                'merchantId' => $result['merchantId']
            ]);
        } else {
            $this->sendError('Failed to create order: ' . $result['error'], 500);
        }
    }
    
    /**
     * Check status endpoint
     */
    private function checkStatus() {
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!$input || !isset($input['orderId'])) {
            $this->sendError('Missing orderId', 400);
            return;
        }
        
        $orderId = $input['orderId'];
        
        // Check status from PhonePe
        $result = $this->orderService->checkOrderStatus($orderId);
        
        if ($result['success']) {
            $this->sendSuccess([
                'orderId' => $orderId,
                'status' => $result['status']
            ]);
        } else {
            $this->sendError('Failed to check status: ' . $result['error'], 500);
        }
    }
    
    /**
     * Health check endpoint
     */
    private function healthCheck() {
        $this->sendSuccess([
            'status' => 'healthy',
            'timestamp' => date('Y-m-d H:i:s'),
            'service' => 'PhonePe API'
        ]);
    }
    
    /**
     * Save order to database
     */
    private function saveOrderToDatabase($orderData, $result) {
        try {
            $query = "INSERT INTO phonepe_orders (
                order_id, user_id, amount, token, merchant_id, 
                status, created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, 'PENDING', NOW(), NOW())";
            
            $params = [
                $orderData['orderId'],
                $orderData['userId'],
                $orderData['amount'],
                $result['token'],
                $result['merchantId']
            ];
            
            $this->db->execute($query, $params);
        } catch (Exception $e) {
            error_log("Failed to save order to database: " . $e->getMessage());
        }
    }
    
    /**
     * Send success response
     */
    private function sendSuccess($data) {
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'data' => $data
        ]);
    }
    
    /**
     * Send error response
     */
    private function sendError($message, $code = 400) {
        http_response_code($code);
        echo json_encode([
            'success' => false,
            'error' => $message
        ]);
    }
}

// Initialize and handle request
$api = new PhonePeAPI();
$api->handleRequest();
?>
