<?php
/**
 * API: جلب قائمة العملاء (من جدول clients)
 * 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);
    
    // جلب العملاء من جدول clients
    $query = "SELECT 
                c.id,
                c.user_id,
                c.full_name,
                c.email,
                c.phone,
                c.governorate,
                c.city,
                c.address,
                c.backup_phone,
                c.relationship,
                c.photo_path,
                c.total_inspections,
                c.status,
                c.created_at,
                c.updated_at,
                u.username
              FROM clients c
              LEFT JOIN users u ON c.user_id = u.id
              ORDER BY c.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);
}
?>