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

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

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

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

$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']) : '';
$networkType = isset($input['network_type']) ? trim($input['network_type']) : '';
$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;
}

function normalize_datetime($value) {
    if ($value === '') { return null; }
    $value = preg_replace('/\s+/', ' ', $value);
    $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) {
            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();

    // Detect timestamp column for agent_orders
    $timestampColumn = 'created_at';
    $check = $conn->query("SHOW COLUMNS FROM agent_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 ($networkType !== '') {
        $where .= " AND network_type = ?";
        $params[] = $networkType;
        $types .= 's';
    }
    if ($currentStatus !== '') {
        $where .= " AND status = ?";
        $params[] = $currentStatus;
        $types .= 's';
    }
    if ($agentFilter !== '') {
        $where .= " AND agent_id IN (SELECT id FROM agents WHERE username LIKE ?)";
        $params[] = "%" . $agentFilter . "%";
        $types .= 's';
    }
    $sql = "UPDATE agent_orders SET status = ? WHERE $where";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new Exception('Failed to prepare statement: ' . $conn->error);
    }
    $stmt->bind_param($types, ...$params);
    if (!$stmt->execute()) {
        throw new Exception('Failed to execute update: ' . $stmt->error);
    }
    $affected = $stmt->affected_rows;
    $stmt->close();

    $conn->commit();

    echo json_encode([
        'success' => true,
        'message' => "Updated {$affected} agent order(s) to {$status}",
        'affected_rows' => $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()]);
}
?>


