<?php
/**
 * ============================================================
 * ADMIN AJAX: Get Order Details
 * ============================================================
 * Returns order details including items, payments, and history
 */

// 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 AJAX
if (!isAjax()) {
    Response::error('Invalid request', [], 400);
}

// Validate CSRF for GET requests via header
if (!csrf_validate()) {
    Response::csrfError();
}

// Must be admin
if (!isAdminLoggedIn()) {
    Response::unauthorized('অ্যাডমিন লগইন প্রয়োজন');
}

// Load service
require_once APP_PATH . '/services/order_service.php';

// Get order ID
$orderId = (int)($_GET['order_id'] ?? $_POST['order_id'] ?? 0);

if ($orderId < 1) {
    Response::error('অবৈধ অর্ডার');
}

// Get order details
$order = OrderService::getById($orderId);

if (!$order) {
    Response::notFound('অর্ডার পাওয়া যায়নি');
}

// Format data for response
$orderData = [
    'id' => $order['id'],
    'order_no' => $order['order_no'],
    'status' => $order['status'],
    'status_badge' => getOrderStatusBadge($order['status']),
    'payment_status' => $order['payment_status'],
    'payment_badge' => getPaymentStatusBadge($order['payment_status']),
    'payment_method' => $order['payment_method'],
    
    // Customer info
    'customer' => [
        'name' => $order['user_name'],
        'email' => $order['user_email'],
        'phone' => $order['user_phone']
    ],
    
    // Shipping
    'shipping' => [
        'name' => $order['shipping_name'],
        'phone' => $order['shipping_phone'],
        'email' => $order['shipping_email'],
        'address' => $order['shipping_address'],
        'city' => $order['shipping_city'],
        'area' => $order['shipping_area']
    ],
    
    // Amounts
    'subtotal' => $order['subtotal'],
    'vat_percent' => $order['vat_percent'],
    'vat_amount' => $order['vat_amount'],
    'tax_amount' => $order['tax_amount'],
    'discount_amount' => $order['discount_amount'],
    'promo_code' => $order['promo_code'],
    'grand_total' => $order['grand_total'],
    
    // Formatted amounts
    'subtotal_formatted' => formatPrice($order['subtotal']),
    'vat_formatted' => formatPrice($order['vat_amount']),
    'tax_formatted' => formatPrice($order['tax_amount']),
    'discount_formatted' => formatPrice($order['discount_amount']),
    'grand_total_formatted' => formatPrice($order['grand_total']),
    
    'notes' => $order['notes'],
    'created_at' => formatDateTime($order['created_at']),
    
    // Items
    'items' => array_map(function($item) {
        return [
            'product_id' => $item['product_id'],
            'product_name' => $item['product_name'],
            'sku' => $item['product_sku'],
            'unit_price' => $item['unit_price'],
            'unit_price_formatted' => formatPrice($item['unit_price']),
            'qty' => $item['qty'],
            'line_total' => $item['line_total'],
            'line_total_formatted' => formatPrice($item['line_total']),
            'image' => $item['image'] ? UPLOADS_URL . '/products/' . $item['image'] : null
        ];
    }, $order['items']),
    
    // Payments
    'payments' => array_map(function($payment) {
        return [
            'id' => $payment['id'],
            'method' => $payment['method'],
            'sender_mobile' => $payment['sender_mobile'],
            'trx_id' => $payment['trx_id'],
            'amount' => formatPrice($payment['amount']),
            'status' => $payment['status'],
            'status_badge' => getPaymentStatusBadge($payment['status']),
            'submitted_at' => formatDateTime($payment['submitted_at']),
            'verified_by' => $payment['verified_by_name'],
            'verified_at' => $payment['verified_at'] ? formatDateTime($payment['verified_at']) : null,
            'admin_note' => $payment['admin_note']
        ];
    }, $order['payments']),
    
    // Status history
    'status_history' => array_map(function($history) {
        return [
            'status' => $history['status'],
            'note' => $history['note'],
            'changed_by' => $history['changed_by_name'],
            'created_at' => formatDateTime($history['created_at'])
        ];
    }, $order['status_history'])
];

Response::success('Order details retrieved', $orderData);
