<?php
/**
 * External API Order Creation Endpoint
 * Creates orders and sends them to external API
 * Completely separate from role-based pricing system
 */

header('Content-Type: application/json');
require_once '../config.php';
require_once '../app/classes/ExternalAPIOrderService.php';
require_once '../app/classes/ExternalAPIPricingManager.php';

use App\classes\ExternalAPIOrderService;
use App\classes\ExternalAPIPricingManager;

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

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

// Validate required fields
$packageSize = $input['package_size'] ?? $input['bundle_size'] ?? null;
$beneficiaryNumber = $input['beneficiary'] ?? $input['beneficiary_number'] ?? $input['phone'] ?? null;
$networkType = 'mtn'; // Only MTN supported

if (empty($packageSize) || empty($beneficiaryNumber)) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Missing required fields: package_size and beneficiary_number'
    ]);
    exit;
}

// Validate phone number (10 digits starting with 0)
$cleanPhone = preg_replace('/\D/', '', $beneficiaryNumber);
if (strlen($cleanPhone) !== 10 || substr($cleanPhone, 0, 1) !== '0') {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Invalid phone number. Must be exactly 10 digits starting with 0'
    ]);
    exit;
}

$beneficiaryNumber = $cleanPhone;

// Check if agent_id is provided (optional)
$agentId = isset($input['agent_id']) ? intval($input['agent_id']) : null;

// Initialize services
$pricingManager = new ExternalAPIPricingManager($conn);
$orderService = new ExternalAPIOrderService($conn);

// Verify pricing exists
$adminPrice = $pricingManager->getAdminPrice($packageSize, $networkType);
$externalPrice = $pricingManager->getExternalPrice($packageSize, $networkType);

if ($adminPrice === null) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Admin price not set for package: ' . $packageSize
    ]);
    exit;
}

if ($externalPrice === null) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'External API price not available for package: ' . $packageSize
    ]);
    exit;
}

// Create order
$result = $orderService->createOrder($packageSize, $networkType, $beneficiaryNumber, $agentId);

if ($result['success']) {
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'message' => 'Order created and sent to external API',
        'order_id' => $result['order_id'],
        'data' => [
            'order_id' => $result['order_id'],
            'package_size' => $packageSize,
            'beneficiary_number' => $beneficiaryNumber,
            'network_type' => $networkType,
            'admin_price' => $adminPrice,
            'external_api_price' => $externalPrice,
            'profit' => $adminPrice - $externalPrice,
            'status' => 'pending'
        ]
    ]);
} else {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $result['message'] ?? 'Failed to create order'
    ]);
}


