<?php
header('Content-Type: application/json');
require_once '../../include/con_data.php';

session_start();

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);
$order_ids = $data['order_ids'] ?? [];

if (empty($order_ids)) {
    echo json_encode(['status' => 'error', 'message' => 'No IDs provided']);
    exit;
}

$ids = [];
$or_ids = [];

foreach ($order_ids as $id) {
    $id = trim($id);
    if (strpos($id, 'OR_') === 0) {
        $or_ids[] = $conn->real_escape_string($id);
    } else {
        $ids[] = intval($id);
    }
}

$success = true;

if (!empty($ids)) {
    $ids_str = implode(',', $ids);
    $sql = "UPDATE orders SET print_status = 'printed' WHERE id IN ($ids_str)";
    if (!$conn->query($sql)) {
        $success = false;
    }
}

if (!empty($or_ids)) {
    $or_ids_str = "'" . implode("','", $or_ids) . "'";
    $sql = "UPDATE orders SET print_status = 'printed' WHERE OR_id IN ($or_ids_str)";
    if (!$conn->query($sql)) {
        $success = false;
    }
}

echo json_encode(['status' => $success ? 'success' : 'error']);
?>