<?php
// support-chat.php : backend pour enregistrer les messages du chat support
header('Content-Type: application/json; charset=utf-8');
require_once 'config/config.php';
require_once 'config/db.php';

function cleanInput($data) {
    return trim(strip_tags($data));
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $conversation_id = isset($_GET['conversation_id']) ? intval($_GET['conversation_id']) : 0;
    $user_email = cleanInput($_GET['user_email'] ?? '');
    $user_name = cleanInput($_GET['user_name'] ?? '');
    try {
        $db = getDbConnection();
        if ($conversation_id) {
            $stmt = $db->prepare("SELECT * FROM support_chat WHERE conversation_id = ? ORDER BY created_at ASC");
            $stmt->execute([$conversation_id]);
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } else {
            if (!$user_email && !$user_name) {
                echo json_encode([]);
                exit;
            }
            // Recherche stricte : nom ET mail doivent correspondre ensemble
            if ($user_email && $user_name) {
                $stmt = $db->prepare("SELECT conversation_id FROM support_chat WHERE sender='user' AND user_email = ? AND user_name = ? ORDER BY created_at DESC LIMIT 1");
                $stmt->execute([$user_email, $user_name]);
                $conv = $stmt->fetch(PDO::FETCH_ASSOC);
                if ($conv) {
                    // Vérifier si la conversation est clôturée
                    $stmt2 = $db->prepare("SELECT closed FROM support_chat WHERE conversation_id = ? ORDER BY id DESC LIMIT 1");
                    $stmt2->execute([$conv['conversation_id']]);
                    $last = $stmt2->fetch(PDO::FETCH_ASSOC);
                    if ($last && isset($last['closed']) && intval($last['closed']) === 1) {
                        // Si clôturée, ne rien afficher
                        echo json_encode([]); exit;
                    }
                    $conversation_id = $conv['conversation_id'];
                    $stmt = $db->prepare("SELECT * FROM support_chat WHERE conversation_id = ? ORDER BY created_at ASC");
                    $stmt->execute([$conversation_id]);
                    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
                } else {
                    echo json_encode([]); exit;
                }
            } else {
                // Si un seul champ est rempli, ne rien afficher
                echo json_encode([]); exit;
            }
        }
        $history = [];
        foreach($rows as $row) {
            $history[] = [
                'sender' => $row['sender'],
                'user_name' => $row['user_name'],
                'message' => $row['message'],
                'time' => date('d/m/Y H:i',strtotime($row['created_at'])),
                'closed' => isset($row['closed']) ? intval($row['closed']) : 0,
                'conversation_id' => $row['conversation_id']
            ];
        }
        echo json_encode($history);
    } catch(Exception $e) {
        echo json_encode([]);
    }
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_name = cleanInput($_POST['user_name'] ?? '');
    $user_email = cleanInput($_POST['user_email'] ?? '');
    $message = cleanInput($_POST['message'] ?? '');
    $closed = isset($_POST['closed']) ? intval($_POST['closed']) : 0;
    $email_send = isset($_POST['email_send']) ? intval($_POST['email_send']) : 0;
    $demande = cleanInput($_POST['demande'] ?? '');

    if (strlen($user_name) < 2) {
        echo json_encode(['success'=>false,'message'=>'Nom trop court.']);
        exit;
    }

    try {
        $db = getDbConnection();
        // Créer une nouvelle conversation SEULEMENT si la précédente est clôturée
        $stmt = $db->prepare("SELECT conversation_id FROM support_chat WHERE sender='user' AND user_email = ? AND user_name = ? ORDER BY created_at DESC LIMIT 1");
        $stmt->execute([$user_email, $user_name]);
        $conv = $stmt->fetch(PDO::FETCH_ASSOC);
        $newConv = true;
        if ($conv) {
            $stmt2 = $db->prepare("SELECT closed FROM support_chat WHERE conversation_id = ? ORDER BY id DESC LIMIT 1");
            $stmt2->execute([$conv['conversation_id']]);
            $last = $stmt2->fetch(PDO::FETCH_ASSOC);
            if ($last && isset($last['closed']) && intval($last['closed']) !== 1) {
                // Conversation existante non clôturée : réutiliser l'id
                $conversation_id = $conv['conversation_id'];
                $newConv = false;
            }
        }
        if ($newConv) {
            $stmt = $db->query("SELECT MAX(conversation_id) as maxid FROM support_chat");
            $maxid = $stmt->fetch(PDO::FETCH_ASSOC);
            $conversation_id = $maxid && $maxid['maxid'] ? $maxid['maxid'] + 1 : 1;
        }
        // Si c'est une demande d'excuse (formulaire), insérer avec closed=1 et email_send=1
        if($closed === 1 && $demande){
            // Clôturer toutes les conversations de ce client (user_name + user_email)
            $stmt = $db->prepare("UPDATE support_chat SET closed=1, email_send=1 WHERE user_name = ? AND user_email = ? AND closed != 1");
            $stmt->execute([$user_name, $user_email]);
            // Insérer la nouvelle demande
            $stmt = $db->prepare("INSERT INTO support_chat (conversation_id, sender, user_name, user_email, message, closed, email_send, created_at) VALUES (?,?,?,?,?,?,?,NOW())");
            $stmt->execute([$conversation_id, 'user', $user_name, $user_email, $demande, 1, 1]);
            echo json_encode(['success'=>true,'message'=>'Votre demande a été enregistrée. Nous vous répondrons par email dès que possible.']);
            exit;
        }
        // Sinon, message classique
        $stmt = $db->prepare("INSERT INTO support_chat (conversation_id, sender, user_name, user_email, message, created_at) VALUES (?,?,?,?,?,NOW())");
        $stmt->execute([$conversation_id, 'user', $user_name, $user_email, $message]);
        echo json_encode(['success'=>true,'message'=>'Message envoyé !']);
    } catch (Exception $e) {
        echo json_encode(['success'=>false,'message'=>'Erreur serveur.']);
    }
    exit;
}
?>
