<?php
require_once 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $recaptcha_secret = '6LfjpHgrAAAAAJzlkquYjrIOuELa0UzXRy8pzPNJ';
    $recaptcha_response = $_POST['g-recaptcha-response'];
    
    $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$recaptcha_secret&response=$recaptcha_response");
    $response_data = json_decode($response);
    
    if ($response_data->success) {
        $nom = trim($_POST['name']);
        $email = trim($_POST['email']);
        $note = (int)$_POST['rating'];
        $commentaire = trim($_POST['comment']);
        $ip = $_SERVER['REMOTE_ADDR'];
        
        if (!empty($nom) && !empty($email) && !empty($commentaire) && $note >= 1 && $note <= 5) {
            $stmt = $pdo->prepare("INSERT INTO avis (nom, email, note, commentaire, ip_address) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$nom, $email, $note, $commentaire, $ip]);
            
            echo json_encode(['success' => true, 'message' => 'Review added successfully!']);
        } else {
            echo json_encode(['success' => false, 'message' => 'All fields are required.']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid captcha.']);
    }
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action'])) {
    if ($_GET['action'] === 'get_avis') {
        $stmt = $pdo->prepare("SELECT nom, note, commentaire, date_creation FROM avis WHERE approved = 1 ORDER BY date_creation DESC");
        $stmt->execute();
        $avis = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($avis);
        exit;
    }
    
    if ($_GET['action'] === 'get_stats') {
        $stmt = $pdo->prepare("SELECT AVG(note) as moyenne, COUNT(*) as total FROM avis WHERE approved = 1");
        $stmt->execute();
        $stats = $stmt->fetch(PDO::FETCH_ASSOC);
        echo json_encode($stats);
        exit;
    }
}
?>