<?php
require_once __DIR__ . '/../config/user_functions.php';

session_start();
if (!isset($_SESSION['user'])) { header('Location: /smproduce/auth/login.php'); exit; }
require_once __DIR__ . '/../config/users_local.php';
if (!user_has_permission('orders')) {
    http_response_code(403);
    echo "Access denied";
    exit;
}
require_once __DIR__ . '/../config/db_remote.php';

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$to = trim($_GET['to'] ?? '');

$allowed = ['Open','Working On','Shipped'];
if ($id <= 0 || !in_array($to, $allowed, true)) {
    echo "Invalid request.";
    exit;
}

$toEsc = $mysqli->real_escape_string($to);
$sql = "UPDATE orders SET status = '{$toEsc}' WHERE id = {$id} LIMIT 1";
$mysqli->query($sql);

// Redirect back to orders list preserving status filter if present
$redir = '/smproduce/pages/orders.php';
if (!empty($_GET['back_status'])) {
    $bs = urlencode($_GET['back_status']);
    $redir .= '?status=' . $bs;
}
header("Location: {$redir}");
exit;
