<?php
session_start();
require 'config.inc.php'; // $dbh PDO connecté à la base 'annonces'

$input = json_decode(file_get_contents('php://input'), true);
$message = trim($input['message']);
$reply = '';

// Détecter l'intention
if(!isset($_SESSION['mode'])) {
    if(stripos($message,'find')!==false) {
        $_SESSION['mode'] = 'search';
        $reply = 'Super ! what do you search ?';
    } elseif(stripos($message,'insert')!==false) {
        $_SESSION['mode'] = 'add';
        $_SESSION['new_annonce'] = [];
        $reply = 'Perfect! What is the title of your classified ?';
    } else {
        $reply = 'I can help you to "find" ou "insert" new classified.';
    }
} else {
    if($_SESSION['mode'] === 'search') {
        // Recherche simple par titre ou catégorie
        $stmt = $dbh->prepare("SELECT titre, id,ref FROM mondialisa_annonces WHERE titre LIKE ? OR categorie LIKE ? AND statut = 1 LIMIT 5");
        $stmt->execute(['%'.$message.'%','%'.$message.'%']);
        $annonces = $stmt->fetchAll(PDO::FETCH_ASSOC);
        if($annonces){
            $lines = [];
            foreach($annonces as $a){
                $lines[] = $a['titre'].' - <a href="index.php?p=details&ref='.$a['ref'].'">Voir</a>';
            }
            $reply = implode("\n", $lines);
        } else {
            $reply = 'No classified was found.';
        }
        unset($_SESSION['mode']);
    }
    elseif($_SESSION['mode'] === 'add') {
        $fields = ['titre','description','categorie','ville','prix','tel'];
        $nextField = count($_SESSION['new_annonce']);
        
        if($nextField < count($fields)){
            $_SESSION['new_annonce'][$fields[$nextField]] = $message;
            $nextField++;
            if($nextField < count($fields)){
                $prompt = [
                    'titre'=>'description :',
                    'description'=>'category ?',
                    'categorie'=>'City ?',
                    'ville'=>'Price ?',
                    'prix'=>'Tel ?'
                ];
                $reply = $prompt[$fields[$nextField-1]] ?? 'Next question :';
            } else {
                // Enregistrer en DB
                $stmt = $dbh->prepare("INSERT INTO mondialisa_annonces (titre, description, categorie, ville, prix, tel) VALUES (?,?,?,?,?,?)");
                $stmt->execute(array_values($_SESSION['new_annonce']));
                $reply = 'Your classified has been inserted !';
                unset($_SESSION['mode'], $_SESSION['new_annonce']);
            }
        }
    }
}

echo json_encode(['reply'=>$reply]);
