<?php
require_once __DIR__ . '/../../cors.php'; // Enable CORS for React Native
// GET   /api/admin/orders  — list all orders with customer info + items
// PATCH /api/admin/orders  — update order status
require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../middleware/auth.php';
require_once __DIR__ . '/../../../includes/order_stock.php';

requireAdmin();
$db = getDB();

// ---- GET ----
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $orders = $db->query(
        'SELECT o.*, u.name AS customer_name, u.email AS customer_email, u.phone AS customer_phone
         FROM orders o
         JOIN users u ON u.id = o.user_id
         ORDER BY o.created_at DESC'
    )->fetchAll();

    $iStmt = $db->prepare('SELECT * FROM order_items WHERE order_id = ?');
    foreach ($orders as &$order) {
        $iStmt->execute([$order['id']]);
        $order['items'] = $iStmt->fetchAll();
    }
    jsonResponse($orders);
}

// ---- PATCH (update status) ----
if ($_SERVER['REQUEST_METHOD'] === 'PATCH') {
    $body   = getBody();
    $id     = $body['orderId'] ?? $body['id'] ?? '';
    $status = $body['status'] ?? '';

    $allowed = ['pending','confirmed','out_for_delivery','delivered','cancelled'];
    if (!$id)                          jsonError('Order id is required');
    if (!in_array($status, $allowed))  jsonError('Invalid status value');

    $ok = transitionOrderStatusWithStock($db, $id, $status);
    if (!$ok) jsonError('Failed to update order status', 400);

    $stmt = $db->prepare('SELECT * FROM orders WHERE id = ?');
    $stmt->execute([$id]);
    jsonResponse($stmt->fetch());
}

jsonError('Method not allowed', 405);
