<?php
/**
 * AJAX: Place Order (Simplified)
 */
header('Content-Type: application/json; charset=utf-8');

try {
    // Initialize
    define('BASE_PATH', dirname(dirname(dirname(__DIR__))));
    require_once BASE_PATH . '/app/config/config.php';
    
    // Start session
    if (session_status() === PHP_SESSION_NONE) {
        session_name(SESSION_NAME);
        session_start();
    }
    
    // Must be POST
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['success' => false, 'message' => 'Invalid request']);
        exit;
    }

    // Must be logged in
    if (!isLoggedIn()) {
        echo json_encode(['success' => false, 'message' => 'অনুগ্রহ করে প্রথমে লগইন করুন']);
        exit;
    }
    
    // Load services
    require_once APP_PATH . '/services/cart_service.php';
    require_once APP_PATH . '/services/order_service.php';
    require_once APP_PATH . '/services/promo_service.php';
    
    // Get POST data
    $shippingName = trim($_POST['shipping_name'] ?? '');
    $shippingPhone = trim($_POST['shipping_phone'] ?? '');
    $shippingEmail = trim($_POST['shipping_email'] ?? '');
    $shippingCity = trim($_POST['shipping_city'] ?? '');
    $shippingArea = trim($_POST['shipping_area'] ?? '');
    $shippingAddress = trim($_POST['shipping_address'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    $paymentMethod = trim($_POST['payment_method'] ?? '');
    $senderMobile = trim($_POST['sender_mobile'] ?? '');
    $trxId = trim($_POST['trx_id'] ?? '');
    
    // Validate
    $errors = [];
    if (empty($shippingName)) $errors['shipping_name'] = 'নাম আবশ্যক';
    if (empty($shippingPhone)) $errors['shipping_phone'] = 'মোবাইল নম্বর আবশ্যক';
    if (empty($shippingCity)) $errors['shipping_city'] = 'শহর আবশ্যক';
    if (empty($shippingAddress)) $errors['shipping_address'] = 'ঠিকানা আবশ্যক';
    if (empty($paymentMethod)) $errors['payment_method'] = 'পেমেন্ট মেথড নির্বাচন করুন';
    if (empty($senderMobile)) $errors['sender_mobile'] = 'প্রেরকের মোবাইল নম্বর আবশ্যক';
    if (empty($trxId)) $errors['trx_id'] = 'Transaction ID আবশ্যক';
    
    if (!empty($errors)) {
        echo json_encode(['success' => false, 'message' => 'সব তথ্য সঠিকভাবে পূরণ করুন', 'errors' => $errors]);
        exit;
    }
    
    // Check if TRX ID already used
    $stmt = Database::getInstance()->prepare("SELECT id FROM order_payments WHERE trx_id = ?");
    $stmt->execute([$trxId]);
    if ($stmt->fetch()) {
        echo json_encode(['success' => false, 'message' => 'এই Transaction ID ইতিমধ্যে ব্যবহৃত হয়েছে']);
        exit;
    }
    
    // Get cart
    $cartService = new CartService();
    if ($cartService->isEmpty()) {
        echo json_encode(['success' => false, 'message' => 'কার্ট খালি। অনুগ্রহ করে পণ্য যোগ করুন।']);
        exit;
    }
    
    $shippingData = [
        'name' => htmlspecialchars($shippingName),
        'phone' => $shippingPhone,
        'email' => $shippingEmail,
        'city' => $shippingCity,
        'area' => $shippingArea,
        'address' => htmlspecialchars($shippingAddress),
        'notes' => htmlspecialchars($notes)
    ];
    
    // Create order
    $result = OrderService::create(
        getUserId(),
        $shippingData,
        $paymentMethod,
        null
    );
    
    if (!$result['success']) {
        echo json_encode(['success' => false, 'message' => $result['message'] ?? 'অর্ডার তৈরি করতে সমস্যা হয়েছে']);
        exit;
    }
    
    $orderId = $result['order_id'];
    $orderNo = $result['order_no'];
    $grandTotal = $result['grand_total'];
    
    // Submit payment details
    OrderService::submitPayment($orderId, $paymentMethod, $senderMobile, $trxId, $grandTotal);
    
    echo json_encode([
        'success' => true,
        'message' => 'অর্ডার সফলভাবে সম্পন্ন হয়েছে! ধন্যবাদ।',
        'data' => [
            'order_id' => $orderId,
            'order_no' => $orderNo,
            'grand_total' => $grandTotal
        ]
    ]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'ত্রুটি: ' . $e->getMessage()]);
}
