<?php
// Clear any output buffer to prevent JSON corruption
if (ob_get_level()) {
    ob_end_clean();
}

// Start session only if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once '../config.php';
require_once '../app/classes/AdminAuth.php';

$adminAuth = new AdminAuth($conn);

// Ensure JSON response
header('Content-Type: application/json');

// Check if admin is authenticated
if (!$adminAuth->isAuthenticated()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

// Check if request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

// Get JSON input
$raw_input = file_get_contents('php://input');
$input = json_decode($raw_input, true);

// Debug logging
error_log("Agent Bulk Update - Raw input: " . $raw_input);
error_log("Agent Bulk Update - Decoded input: " . json_encode($input));

// If no input from php://input, try to get from POST data (for testing)
if (empty($raw_input) && !empty($_POST)) {
    $input = $_POST;
    error_log("Agent Bulk Update - Using POST data: " . json_encode($input));
}

if (!$input || !isset($input['order_ids']) || !isset($input['status'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit;
}

$order_ids = $input['order_ids'];
$new_status = $input['status'];

// Debug logging
error_log("Agent Bulk Update - Order IDs: " . json_encode($order_ids));
error_log("Agent Bulk Update - Status: " . $new_status);

// Validate status
$valid_statuses = ['pending', 'delivered', 'failed'];
if (!in_array($new_status, $valid_statuses)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid status']);
    exit;
}

// Validate order IDs
if (!is_array($order_ids) || empty($order_ids)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'No orders selected']);
    exit;
}

// Sanitize order IDs
error_log("Agent Bulk Update - Before sanitization: " . json_encode($order_ids));
$sanitized_ids = array_map('intval', $order_ids);
error_log("Agent Bulk Update - After intval: " . json_encode($sanitized_ids));
$sanitized_ids = array_filter($sanitized_ids, function($id) {
    return $id > 0;
});
error_log("Agent Bulk Update - After filtering: " . json_encode($sanitized_ids));

if (empty($sanitized_ids)) {
    error_log("Agent Bulk Update - No valid IDs after sanitization");
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid order IDs']);
    exit;
}

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Get old statuses for orders before updating (for webhook notifications)
    $placeholders = str_repeat('?,', count($sanitized_ids) - 1) . '?';
    $selectStmt = $conn->prepare("SELECT id, status FROM agent_orders WHERE id IN ($placeholders)");
    if (!$selectStmt) {
        throw new Exception("Failed to prepare select statement: " . $conn->error);
    }
    
    $selectTypes = str_repeat('i', count($sanitized_ids));
    $selectStmt->bind_param($selectTypes, ...$sanitized_ids);
    $selectStmt->execute();
    $result = $selectStmt->get_result();
    
    $oldStatuses = [];
    while ($row = $result->fetch_assoc()) {
        $oldStatuses[$row['id']] = $row['status'];
    }
    $selectStmt->close();
    
    // Prepare the update statement for agent_orders table
    $stmt = $conn->prepare("UPDATE agent_orders SET status = ?, status_updated_at = NOW() WHERE id IN ($placeholders)");
    
    if (!$stmt) {
        throw new Exception("Failed to prepare statement: " . $conn->error);
    }
    
    // Bind parameters
    $params = array_merge([$new_status], $sanitized_ids);
    $types = 's' . str_repeat('i', count($sanitized_ids));
    $stmt->bind_param($types, ...$params);
    
    // Execute the update
    if (!$stmt->execute()) {
        throw new Exception("Failed to execute update: " . $stmt->error);
    }
    
    $affected_rows = $stmt->affected_rows;
    $stmt->close();
    
    // Commit transaction
    $conn->commit();
    
    // Webhook sending disabled for agent order status updates.
    $webhookResults = [];
    
    echo json_encode([
        'success' => true, 
        'message' => "Successfully updated $affected_rows agent order(s) to $new_status",
        'affected_rows' => $affected_rows,
        'webhooks_sent' => count($webhookResults),
        'webhook_results' => $webhookResults
    ]);
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
