<?php
// Admin/v2/financial/settlements.php
require_once __DIR__ . '/../../../connect.php';

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

try {
    // جلب السائقين الذين لديهم مستحقات أو مديونية
    // الحسبة: إجمالي (price_for_driver) من الرحلات المكتملة
    $stmt = $con->prepare("
        SELECT 
            d.id, d.first_name, d.last_name, d.phone,
            SUM(r.price_for_driver) as total_earned,
            COUNT(r.id) as total_rides
        FROM driver d
        LEFT JOIN ride r ON d.id = r.driver_id AND r.status = 'Finished'
        GROUP BY d.id
        HAVING total_earned > 0
        ORDER BY total_earned DESC
        LIMIT 50
    ");
    $stmt->execute();
    $drivers = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // فك تشفير البيانات
    foreach ($drivers as &$driver) {
        $driver['first_name'] = $encryptionHelper->decryptData($driver['first_name']);
        $driver['last_name'] = $encryptionHelper->decryptData($driver['last_name']);
        $driver['phone'] = $encryptionHelper->decryptData($driver['phone']);
    }

    echo json_encode([
        'status' => 'success',
        'data' => $drivers
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>
