<?php
// test_search.php - Test de la recherche par dates
require_once 'config.php';

echo "<h3>Test de recherche par dates</h3>";

// Simuler une recherche
$dateDebut = $_GET['dateDebut'] ?? '2024-01-01';
$dateFin = $_GET['dateFin'] ?? '2024-12-31';

echo "<p>Date début: $dateDebut</p>";
echo "<p>Date fin: $dateFin</p>";

try {
    $conditions = [];
    $params = [];
    
    if (!empty($dateDebut)) {
        $conditions[] = "dmv >= :dateDebut";
        $params[':dateDebut'] = $dateDebut;
        echo "<p>Condition début ajoutée: dmv >= $dateDebut</p>";
    }
    
    if (!empty($dateFin)) {
        $conditions[] = "dmv <= :dateFin";
        $params[':dateFin'] = $dateFin;
        echo "<p>Condition fin ajoutée: dmv <= $dateFin</p>";
    }
    
    $whereClause = empty($conditions) ? '' : 'WHERE ' . implode(' AND ', $conditions);
    
    $sql = "SELECT ID, CodePesee, dmv, NomClient FROM pesee $whereClause ORDER BY dmv DESC LIMIT 5";
    echo "<p>SQL: <code>$sql</code></p>";
    
    $pdo = DatabaseConfig::getConnection();
    $stmt = $pdo->prepare($sql);
    
    foreach ($params as $param => $value) {
        $stmt->bindValue($param, $value, PDO::PARAM_STR);
        echo "<p>Paramètre: $param = $value</p>";
    }
    
    $stmt->execute();
    $results = $stmt->fetchAll();
    
    echo "<h4>Résultats (" . count($results) . "):</h4>";
    if (!empty($results)) {
        echo "<table border='1'>";
        echo "<tr><th>ID</th><th>Code</th><th>Date (dmv)</th><th>Client</th></tr>";
        foreach ($results as $row) {
            echo "<tr>";
            echo "<td>{$row['ID']}</td>";
            echo "<td>{$row['CodePesee']}</td>";
            echo "<td>{$row['dmv']}</td>";
            echo "<td>{$row['NomClient']}</td>";
            echo "</tr>";
        }
        echo "</table>";
    } else {
        echo "<p>Aucun résultat</p>";
    }
    
    // Test format de date dans la base
    echo "<h4>Exemple de dates dans la base:</h4>";
    $stmt2 = $pdo->prepare("SELECT dmv, CodePesee FROM pesee ORDER BY ID DESC LIMIT 3");
    $stmt2->execute();
    $examples = $stmt2->fetchAll();
    
    foreach ($examples as $ex) {
        echo "<p>dmv: {$ex['dmv']} (Code: {$ex['CodePesee']})</p>";
    }
    
} catch (Exception $e) {
    echo "<p style='color:red'>Erreur: " . $e->getMessage() . "</p>";
}
?>

<p><a href="test_search.php?dateDebut=2024-09-01&dateFin=2024-09-30">Test Sept 2024</a></p>
<p><a href="test_search.php?dateDebut=2024-09-04&dateFin=2024-09-05">Test Hier/Aujourd'hui</a></p>