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

header('Content-Type: application/json');

$action = $_GET['action'] ?? '';

if ($action === 'properties') {
    $db = getDB();
    $stmt = $db->query("SELECT p.*, (SELECT image_path FROM property_images pi WHERE pi.property_id = p.id ORDER BY is_primary DESC, sort_order ASC LIMIT 1) as image FROM properties p WHERE p.publication_status = 'publie' ORDER BY created_at DESC");
    echo json_encode(['status' => 'success', 'data' => $stmt->fetchAll()]);
    exit;
}

if ($action === 'zones') {
    $zones = getZones();
    echo json_encode(['status' => 'success', 'data' => $zones]);
    exit;
}

if ($action === 'types') {
    $types = getPropertyTypes();
    echo json_encode(['status' => 'success', 'data' => $types]);
    exit;
}

if ($action === 'contact' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = sanitize($_POST['name'] ?? '');
    $email = filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL);
    $message = sanitize($_POST['message'] ?? '');
    $profil = sanitize($_POST['profil_je_suis'] ?? 'Autre');
    
    if (!$name || !$email || !$message) {
        echo json_encode(['status' => 'error', 'message' => 'Validation des champs échouée.']);
        exit;
    }
    
    $db = getDB();
    $stmt = $db->prepare("INSERT INTO contact_messages (nom, email, message, profil_je_suis) VALUES (?, ?, ?, ?)");
    $stmt->execute([$name, $email, $message, $profil]);
    
    echo json_encode(['status' => 'success', 'message' => 'Message envoyé avec succès.']);
    exit;
}

echo json_encode(['status' => 'error', 'message' => 'Action non reconnue']);
exit;
