<?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("Bulk Update - Raw input: " . $raw_input);
error_log("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("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("Bulk Update - Order IDs: " . json_encode($order_ids));
error_log("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("Bulk Update - Before sanitization: " . json_encode($order_ids));
error_log("Bulk Update - Order IDs type: " . gettype($order_ids));
error_log("Bulk Update - Order IDs count: " . count($order_ids));

$sanitized_ids = array_map('intval', $order_ids);
error_log("Bulk Update - After intval: " . json_encode($sanitized_ids));

$sanitized_ids = array_filter($sanitized_ids, function($id) {
    $is_valid = $id > 0;
    error_log("Bulk Update - ID $id is valid: " . ($is_valid ? 'yes' : 'no'));
    return $is_valid;
});
error_log("Bulk Update - After filtering: " . json_encode($sanitized_ids));
error_log("Bulk Update - Filtered count: " . count($sanitized_ids));

if (empty($sanitized_ids)) {
    error_log("Bulk Update - No valid IDs after sanitization");
    
    // Check if all IDs are 0 - this might indicate a database issue
    $all_zeros = true;
    foreach ($order_ids as $id) {
        if ($id !== '0' && $id !== 0) {
            $all_zeros = false;
            break;
        }
    }
    
    if ($all_zeros) {
        error_log("Bulk Update - All order IDs are 0, this indicates a database issue");
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Order IDs are invalid (all zeros). This indicates a database issue. Please check the orders table structure.', 'debug' => [
            'original_ids' => $order_ids,
            'sanitized_ids' => $sanitized_ids,
            'count' => count($sanitized_ids),
            'all_zeros' => true
        ]]);
        exit;
    }
    
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid order IDs', 'debug' => [
        'original_ids' => $order_ids,
        'sanitized_ids' => $sanitized_ids,
        'count' => count($sanitized_ids)
    ]]);
    exit;
}

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Create placeholders for the IN clause
    $placeholders = str_repeat('?,', count($sanitized_ids) - 1) . '?';
    
    // Get old statuses for agent_orders before updating (for webhook notifications)
    $selectAgentStmt = $conn->prepare("SELECT id, status FROM agent_orders WHERE id IN ($placeholders)");
    $oldAgentStatuses = [];
    if ($selectAgentStmt) {
        $selectTypes = str_repeat('i', count($sanitized_ids));
        $selectAgentStmt->bind_param($selectTypes, ...$sanitized_ids);
        $selectAgentStmt->execute();
        $result = $selectAgentStmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $oldAgentStatuses[$row['id']] = $row['status'];
        }
        $selectAgentStmt->close();
    }
    
    $total_affected = 0;
    $table_type = isset($input['table_type']) ? $input['table_type'] : null;
    
    // If table_type is specified, only update that table
    if ($table_type === 'orders') {
        // Only update orders table
        $sql_orders = "UPDATE orders SET status = ? WHERE id IN ($placeholders)";
        error_log("Bulk Update - Orders SQL: $sql_orders");
        
        $stmt_orders = $conn->prepare($sql_orders);
        if ($stmt_orders) {
            $params = array_merge([$new_status], $sanitized_ids);
            $types = 's' . str_repeat('i', count($sanitized_ids));
            
            $bind_result = $stmt_orders->bind_param($types, ...$params);
            if ($bind_result && $stmt_orders->execute()) {
                $orders_affected = $stmt_orders->affected_rows;
                $total_affected += $orders_affected;
                error_log("Bulk Update - Orders affected: $orders_affected");
            }
            $stmt_orders->close();
        }
    } elseif ($table_type === 'agent_orders') {
        // Only update agent_orders table
        $sql_agent_orders = "UPDATE agent_orders SET status = ?, status_updated_at = NOW() WHERE id IN ($placeholders)";
        error_log("Bulk Update - Agent Orders SQL: $sql_agent_orders");
        
        $stmt_agent_orders = $conn->prepare($sql_agent_orders);
        if ($stmt_agent_orders) {
            $params = array_merge([$new_status], $sanitized_ids);
            $types = 's' . str_repeat('i', count($sanitized_ids));
            
            $bind_result = $stmt_agent_orders->bind_param($types, ...$params);
            if ($bind_result && $stmt_agent_orders->execute()) {
                $agent_orders_affected = $stmt_agent_orders->affected_rows;
                $total_affected += $agent_orders_affected;
                error_log("Bulk Update - Agent Orders affected: $agent_orders_affected");
            }
            $stmt_agent_orders->close();
        }
    } else {
        // Try to update both tables (backward compatibility)
        $sql_orders = "UPDATE orders SET status = ? WHERE id IN ($placeholders)";
        error_log("Bulk Update - Orders SQL: $sql_orders");
        
        $stmt_orders = $conn->prepare($sql_orders);
        if ($stmt_orders) {
            $params = array_merge([$new_status], $sanitized_ids);
            $types = 's' . str_repeat('i', count($sanitized_ids));
            
            $bind_result = $stmt_orders->bind_param($types, ...$params);
            if ($bind_result && $stmt_orders->execute()) {
                $orders_affected = $stmt_orders->affected_rows;
                $total_affected += $orders_affected;
                error_log("Bulk Update - Orders affected: $orders_affected");
            }
            $stmt_orders->close();
        }
        
        // Try to update agent_orders table
        $sql_agent_orders = "UPDATE agent_orders SET status = ?, status_updated_at = NOW() WHERE id IN ($placeholders)";
        error_log("Bulk Update - Agent Orders SQL: $sql_agent_orders");
        
        $stmt_agent_orders = $conn->prepare($sql_agent_orders);
        if ($stmt_agent_orders) {
            $params = array_merge([$new_status], $sanitized_ids);
            $types = 's' . str_repeat('i', count($sanitized_ids));
            
            $bind_result = $stmt_agent_orders->bind_param($types, ...$params);
            if ($bind_result && $stmt_agent_orders->execute()) {
                $agent_orders_affected = $stmt_agent_orders->affected_rows;
                $total_affected += $agent_orders_affected;
                error_log("Bulk Update - Agent Orders affected: $agent_orders_affected");
            }
            $stmt_agent_orders->close();
        }
    }
    
    // Commit transaction
    $conn->commit();
    
    // Webhook sending disabled for order management status updates.
    $webhookResults = [];
    
    error_log("Bulk Update - Total affected: $total_affected rows");
    
    echo json_encode([
        'success' => true, 
        'message' => "Successfully updated $total_affected order(s) to $new_status",
        'affected_rows' => $total_affected,
        'webhooks_sent' => count($webhookResults),
        'webhook_results' => $webhookResults
    ]);
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    error_log("Bulk Update - Error: " . $e->getMessage());
    
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
