<?php
require_once '../config.php';
require_once '../../includes/Auth.php';
require_once '../../includes/Shop.php';

$auth = new Auth();
$user = $auth->requireAuth();
$shop = new Shop();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    $order_id = $input['order_id'] ?? null;
    $status = $input['status'] ?? null;
    $shop_id = $input['shop_id'] ?? null;

    if (!$order_id || !$status || !$shop_id) {
        jsonResponse(['success' => false, 'message' => 'Order ID, Shop ID, and status are required'], 400);
    }

    // Security check: ensure the current user owns the shop
    if (!$auth->hasRole('admin') && !$shop->isOwner($shop_id, $user['id'])) {
        jsonResponse(['success' => false, 'message' => 'Unauthorized'], 403);
    }

    try {
        // The update method should also verify the order belongs to the shop
        $success = $shop->updateOrderStatus($order_id, $status, $shop_id);
        jsonResponse(['success' => $success, 'message' => $success ? 'Status updated' : 'Failed to update status']);
    } catch (Exception $e) {
        jsonResponse(['success' => false, 'message' => $e->getMessage()], 500);
    }
}