<?php
require_once '../config.php';
require_once '../app/classes/AdminAuth.php';

// Initialize authentication
$auth = new AdminAuth($conn);

// Check if user is authenticated
if (!$auth->isAuthenticated()) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

// Set content type to JSON
header('Content-Type: application/json');

// Get search parameters
$type = $_GET['type'] ?? '';
$query = $_GET['q'] ?? '';

// Validate type
if (!in_array($type, ['delivered', 'cleanup'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid search type']);
    exit;
}

try {
    $orders = [];
    
    if ($type === 'delivered') {
        if (!empty($query)) {
            $search_term = mysqli_real_escape_string($conn, $query);
            $sql = "SELECT * FROM completed_databundle_orders WHERE status = 'delivered' AND (reference LIKE '%$search_term%' OR momo_name LIKE '%$search_term%' OR momo_number LIKE '%$search_term%' OR package LIKE '%$search_term%') ORDER BY processed_at DESC LIMIT 100";
        } else {
            $sql = "SELECT * FROM completed_databundle_orders WHERE status = 'delivered' ORDER BY processed_at DESC LIMIT 50";
        }
        
        $result = mysqli_query($conn, $sql);
        if ($result) {
            while ($row = mysqli_fetch_assoc($result)) {
                $orders[] = $row;
            }
        }
    } elseif ($type === 'cleanup') {
        if (!empty($query)) {
            $search_term = mysqli_real_escape_string($conn, $query);
            $sql = "SELECT * FROM cleanup_databundle_orders WHERE (reference LIKE '%$search_term%' OR momo_name LIKE '%$search_term%' OR momo_number LIKE '%$search_term%' OR package LIKE '%$search_term%' OR reason LIKE '%$search_term%') ORDER BY moved_at DESC LIMIT 100";
        } else {
            $sql = "SELECT * FROM cleanup_databundle_orders ORDER BY moved_at DESC LIMIT 50";
        }
        
        $result = mysqli_query($conn, $sql);
        if ($result) {
            while ($row = mysqli_fetch_assoc($result)) {
                $orders[] = $row;
            }
        }
    }
    
    echo json_encode([
        'success' => true,
        'orders' => $orders,
        'count' => count($orders)
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
