<?php
session_start();
header('Content-Type: application/json');

require_once "db.php"; // your DB connection

// Only allow admin
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Get POST data
$order_id = intval($_POST['id'] ?? 0);          // match admin-orders.php
$new_status = trim($_POST['status'] ?? '');

// Validate
$valid_statuses = ['Pending', 'Processing', 'Shipped', 'Completed', 'Cancelled'];
if (!$order_id || !in_array($new_status, $valid_statuses)) {
    echo json_encode(['success' => false, 'message' => 'Invalid input']);
    exit;
}

// Check order exists
$stmt = $conn->prepare("SELECT id FROM orders WHERE id=?");
$stmt->bind_param("i", $order_id);
$stmt->execute();
$res = $stmt->get_result();
if ($res->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Order not found']);
    exit;
}
$stmt->close();

// Update status
$stmt = $conn->prepare("UPDATE orders SET status=? WHERE id=?");
$stmt->bind_param("si", $new_status, $order_id);
$success = $stmt->execute();
$stmt->close();

if ($success) {
    echo json_encode(['success' => true, 'message' => 'Order status updated']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to update order']);
}
