<?php
// FINAL SCRIPT: update_order_status.php

ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

require 'db_connect.php';

header('Content-Type: application/json');
ob_clean();

$response = [];

if (!isset($conn) || $conn->connect_error) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Server Error: Database connection failed.';
    echo json_encode($response);
    exit;
}

if (!isset($_POST['order_id']) || !isset($_POST['status'])) {
    http_response_code(400);
    $response['status'] = 'error';
    $response['message'] = 'Required fields (order_id, status) are missing.';
    echo json_encode($response);
    exit;
}

$orderId = intval($_POST['order_id']);
$newStatus = trim($_POST['status']);

try {
    $sql = "UPDATE orders SET status = ? WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("si", $newStatus, $orderId);

    if ($stmt->execute()) {
        if ($stmt->affected_rows > 0) {
            $response['status'] = 'success';
            $response['message'] = 'Order status updated successfully.';
        } else {
            $response['status'] = 'error';
            $response['message'] = 'Order not found or status is already the same.';
        }
    } else {
        throw new Exception('Query execution failed.');
    }
    $stmt->close();

} catch (Exception $e) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Failed to update status: ' . $e->getMessage();
}

echo json_encode($response);
$conn->close();
exit;
?>