<?php
/**
 * ============================================================
 * ADMIN AJAX: Change Order Status
 * ============================================================
 * Updates order status (Pending → Processing → Shipped → Delivered)
 */

// 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') {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

// Must be admin
if (!isAdminLoggedIn()) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'অ্যাডমিন লগইন প্রয়োজন']);
    exit;
}

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

// Get data
$orderId = (int)post('order_id');
$status = sanitize(post('status'));
$note = sanitize(post('note'));

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

$validStatuses = ['Pending', 'Processing', 'Shipped', 'Delivered', 'Cancelled'];
if (!in_array($status, $validStatuses)) {
    Response::error('অবৈধ স্ট্যাটাস');
}

// Update status
$result = OrderService::updateStatus($orderId, $status, getAdminId(), $note);

if ($result['success']) {
    Response::success($result['message'], [
        'order_id' => $orderId,
        'new_status' => $status
    ]);
} else {
    Response::error($result['message']);
}
