<?php
/**
 * API: جلب قائمة العملاء (المستخدمين من نوع client)
 * GET /api/admin/endpoints/get_clients.php
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// إعدادات الاتصال بقاعدة البيانات
$host = "localhost";
$dbname = "digitals_autotester_db";
$username = "digitals";
$password = "bassam.bassam";

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // جلب العملاء من جدول users (حيث role = 'client')
    $query = "SELECT 
                u.id,
                u.username,
                u.full_name,
                u.email,
                u.phone,
                u.governorate,
                u.area,
                u.address,
                u.backup_phone,
                u.relationship,
                u.is_active,
                u.request_number,
                u.created_at,
                u.updated_at,
                (SELECT COUNT(*) FROM inspection_requests_new WHERE customer_email = u.email OR customer_phone = u.phone) as total_inspections
              FROM users u
              WHERE u.role = 'client'
              ORDER BY u.created_at DESC";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    $clients = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $clients,
        'total' => count($clients),
        'timestamp' => date('Y-m-d H:i:s')
    ], JSON_UNESCAPED_UNICODE);
    
} catch(PDOException $e) {
    error_log("Database error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}
?>