<?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 = [
        'name' => 's.name',
        'owner_name' => 'u.name',
        'location' => 's.location',
        'is_approved' => 's.is_approved',
        'created_at' => 's.created_at'
    ];
    $sort_by = $sort_by_map[$_GET['sort_by'] ?? 'created_at'] ?? 's.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 shops s JOIN users u ON s.owner_id = u.id";
    $whereSql = "";

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

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

    // Get paginated results
    $stmt = $db->query("SELECT s.*, u.name as owner_name " . $baseSql . " " . $whereSql . " " . $orderBySql . " LIMIT " . (int)$limit . " OFFSET " . (int)$offset, $params);
    $shops = $stmt->fetchAll(PDO::FETCH_ASSOC);

    jsonResponse(['success' => true, 'shops' => $shops, 'pagination' => [
        'total_items' => $totalItems, 'total_pages' => $totalPages, 'current_page' => $page, 'limit' => $limit
    ]]);
} catch (Exception $e) {
    jsonResponse(['success' => false, 'message' => $e->getMessage()], 500);
}
?>