<?php
require_once __DIR__ . '/../../connect.php';

if ($role !== 'admin' && $role !== 'super_admin') {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized: Admin access required']);
    exit;
}

$page = max(1, (int) filterRequest('page'));
$limit = 50;
$offset = ($page - 1) * $limit;

$sql = "
SELECT
    d.phone,
    d.id,
    d.name_arabic,
    dt.token
FROM
    `driver` d
LEFT JOIN driverToken dt ON
    dt.captain_id = d.id
LIMIT :lim OFFSET :off
";

$stmt = $con->prepare($sql);
$stmt->bindValue(':lim', $limit, PDO::PARAM_INT);
$stmt->bindValue(':off', $offset, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

$countStmt = $con->query("SELECT COUNT(*) FROM `driver`");
$total = $countStmt->fetchColumn();

foreach ($result as &$row) {
    $row['phone'] = $encryptionHelper->decryptData($row['phone']);
    if (!empty($row['token'])) {
        $row['token'] = $encryptionHelper->decryptData($row['token']);
    }
}

if ($stmt->rowCount() > 0) {
    jsonSuccess([
        'data' => $result,
        'total' => (int) $total,
        'page' => $page,
        'pages' => (int) ceil($total / $limit),
    ]);
} else {
    jsonError("No records found");
}
