<?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');

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

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

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

if (!$input) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid JSON body']);
    exit;
}

$start = isset($input['start']) ? trim($input['start']) : '';
$end = isset($input['end']) ? trim($input['end']) : '';
$status = isset($input['status']) ? trim($input['status']) : '';
$currentStatus = isset($input['current_status']) ? trim($input['current_status']) : '';
$agentFilter = isset($input['agent_filter']) ? trim($input['agent_filter']) : '';

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

// Validate and normalize datetimes (expects 'YYYY-MM-DD HH:MM' or 'YYYY-MM-DD')
function normalize_datetime($value) {
    if ($value === '') { return null; }
    $value = preg_replace('/\s+/', ' ', $value);
    // Try multiple formats
    $formats = ['Y-m-d H:i:s', 'Y-m-d H:i', 'Y-m-d'];
    foreach ($formats as $fmt) {
        $dt = DateTime::createFromFormat($fmt, $value);
        if ($dt instanceof DateTime) {
            // Add seconds if missing
            return $dt->format('Y-m-d H:i:s');
        }
    }
    return null;
}

$start_dt = normalize_datetime($start);
$end_dt = normalize_datetime($end);

if (!$start_dt || !$end_dt) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid start or end datetime']);
    exit;
}

if ($start_dt > $end_dt) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Start datetime must be before end datetime']);
    exit;
}

try {
    $conn->begin_transaction();

    $total_affected = 0;

    // Update orders table
    $timestampColumn = 'created_at';
    $check = $conn->query("SHOW COLUMNS FROM orders LIKE 'created_at'");
    if (!$check || $check->num_rows === 0) {
        $timestampColumn = 'order_date';
    }
    if ($check) { $check->close(); }

    $where = "{$timestampColumn} BETWEEN ? AND ?";
    $params = [$status, $start_dt, $end_dt];
    $types = 'sss';

    if ($currentStatus !== '') {
        $where .= " AND status = ?";
        $params[] = $currentStatus;
        $types .= 's';
    }

    if ($agentFilter !== '') {
        $where .= " AND username LIKE ?";
        $params[] = "%" . $agentFilter . "%";
        $types .= 's';
    }

    $sql_orders = "UPDATE orders SET status = ? WHERE $where";
    $stmt_orders = $conn->prepare($sql_orders);
    if ($stmt_orders) {
        $stmt_orders->bind_param($types, ...$params);
        if ($stmt_orders->execute()) {
            $orders_affected = $stmt_orders->affected_rows;
            $total_affected += $orders_affected;
        }
        $stmt_orders->close();
    }

    // Update agent_orders table
    $agentTimestampColumn = 'created_at';
    $checkAgent = $conn->query("SHOW COLUMNS FROM agent_orders LIKE 'created_at'");
    if (!$checkAgent || $checkAgent->num_rows === 0) {
        $agentTimestampColumn = 'order_date';
    }
    if ($checkAgent) { $checkAgent->close(); }

    $agent_where = "{$agentTimestampColumn} BETWEEN ? AND ?";
    $agent_params = [$status, $start_dt, $end_dt];
    $agent_types = 'sss';

    if ($currentStatus !== '') {
        $agent_where .= " AND status = ?";
        $agent_params[] = $currentStatus;
        $agent_types .= 's';
    }

    if ($agentFilter !== '') {
        $agent_where .= " AND agent_name LIKE ?";
        $agent_params[] = "%" . $agentFilter . "%";
        $agent_types .= 's';
    }

    $sql_agent_orders = "UPDATE agent_orders SET status = ? WHERE $agent_where";
    $stmt_agent_orders = $conn->prepare($sql_agent_orders);
    if ($stmt_agent_orders) {
        $stmt_agent_orders->bind_param($agent_types, ...$agent_params);
        if ($stmt_agent_orders->execute()) {
            $agent_orders_affected = $stmt_agent_orders->affected_rows;
            $total_affected += $agent_orders_affected;
        }
        $stmt_agent_orders->close();
    }

    $conn->commit();

    echo json_encode([
        'success' => true,
        'message' => "Updated {$total_affected} order(s) to {$status}",
        'affected_rows' => $total_affected,
        'range' => [$start_dt, $end_dt]
    ]);
} catch (Exception $e) {
    $conn->rollback();
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>


