<?php
// api/get_clients.php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once __DIR__ . '/../../config.php';

try {
    $sql = "
        SELECT 
            Id,
            ClientId,
            FullName,
            Phone,
            Email,
            CreatedAt
        FROM Clients
        ORDER BY Id DESC
    ";

    $stmt = $pdo->query($sql);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Normalize CreatedAt to ISO 8601 (e.g. 2025-01-14T12:34:56)
    foreach ($rows as &$row) {
        if (!empty($row['CreatedAt'])) {
            // MySQL default format 'Y-m-d H:i:s'
            $dt = DateTime::createFromFormat('Y-m-d H:i:s', $row['CreatedAt']);
            if ($dt !== false) {
                $row['CreatedAt'] = $dt->format('c'); // ISO 8601
            }
        }
    }
    unset($row);

    echo json_encode($rows);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error'   => 'Failed to load clients',
        'details' => $e->getMessage()
    ]);
}
