<?php
require_once '../config.php';
require_once '../../includes/Auth.php';
require_once '../../includes/Database.php';

$auth = new Auth();
$auth->requireRole('admin');

try {
    $db = new Database();

    // Pagination parameters
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = 10; // Items per page
    $offset = ($page - 1) * $limit;

    $searchTerm = $_GET['search'] ?? '';
    $params = [];
    $countParams = [];

    // Sorting parameters
    $sort_by_map = [
        'tracking_id' => 'd.tracking_id',
        'customer_name' => 'c.name',
        'rider_name' => 'r.name',
        'status' => 'd.status',
        'price' => 'd.price',
        'created_at' => 'd.created_at'
    ];
    $sort_by = $sort_by_map[$_GET['sort_by'] ?? 'created_at'] ?? 'd.created_at';
    $sort_dir = in_array(strtolower($_GET['sort_dir'] ?? ''), ['asc', 'desc']) ? strtoupper($_GET['sort_dir']) : 'DESC';
    $orderBySql = "ORDER BY {$sort_by} {$sort_dir}";

    $baseSql = "FROM deliveries d JOIN users c ON d.customer_id = c.id LEFT JOIN users r ON d.rider_id = r.id";
    $whereSql = "";

    if (!empty($searchTerm)) {
        $whereSql = " WHERE d.tracking_id LIKE ? OR c.name LIKE ? OR r.name LIKE ?";
        $likeTerm = "%$searchTerm%";
        $params[] = $likeTerm;
        $params[] = $likeTerm;
        $params[] = $likeTerm;
        $countParams = $params;
    }

    // Get total count for pagination
    $countStmt = $db->query("SELECT COUNT(d.id) as total " . $baseSql . " " . $whereSql, $countParams);
    $totalItems = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];
    $totalPages = ceil($totalItems / $limit);

    // Get paginated results
    $stmt = $db->query("SELECT d.*, c.name as customer_name, r.name as rider_name " . $baseSql . " " . $whereSql . " " . $orderBySql . " LIMIT " . (int)$limit . " OFFSET " . (int)$offset, $params);
    $deliveries = $stmt->fetchAll(PDO::FETCH_ASSOC);

    jsonResponse(['success' => true, 'deliveries' => $deliveries, 'pagination' => [
        'total_items' => $totalItems, 'total_pages' => $totalPages, 'current_page' => $page, 'limit' => $limit
    ]]);

} catch (Exception $e) {
    jsonResponse(['success' => false, 'message' => $e->getMessage()], 500);
}
?>