<?php
require_once 'auth_check.php';
require_once 'db.php';

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

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Non autorisé']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Méthode non autorisée']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['ticket_id']) || !isset($input['message'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Données manquantes']);
    exit;
}

$ticketId = intval($input['ticket_id']);
$message = trim($input['message']);
$userId = $_SESSION['user_id'];
$isStaff = isset($_SESSION['role']) && $_SESSION['role'] == 1 ? 1 : 0;

if (empty($message)) {
    http_response_code(400);
    echo json_encode(['error' => 'Le message ne peut pas être vide']);
    exit;
}

try {
    $db1 = getDB1Connection();
    
    $ticketCheckQuery = "SELECT id FROM support_tickets WHERE id = ?";
    $stmt = $db1->prepare($ticketCheckQuery);
    $stmt->execute([$ticketId]);
    
    if (!$stmt->fetch()) {
        http_response_code(404);
        echo json_encode(['error' => 'Ticket non trouvé']);
        exit;
    }
    
    $insertQuery = "INSERT INTO ticket_responses (ticket_id, user_id, response, is_staff, created_at) 
                    VALUES (?, ?, ?, ?, NOW())";
    $stmt = $db1->prepare($insertQuery);
    $result = $stmt->execute([$ticketId, $userId, $message, $isStaff]);
    
    if ($result) {
        if ($isStaff) {
            $ticketOwnerQuery = "SELECT user_id FROM support_tickets WHERE id = ?";
            $stmt = $db1->prepare($ticketOwnerQuery);
            $stmt->execute([$ticketId]);
            $ticketOwner = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($ticketOwner && $ticketOwner['user_id'] != $userId) {
                $notificationQuery = "INSERT INTO ticket_notifications (ticket_id, user_id, message, created_at) 
                                     VALUES (?, ?, ?, NOW())";
                $stmt = $db1->prepare($notificationQuery);
                $stmt->execute([
                    $ticketId, 
                    $ticketOwner['user_id'], 
                    "Nouvelle réponse sur votre ticket #" . $ticketId
                ]);
            }
        }
        
        echo json_encode(['success' => true, 'message' => 'Réponse envoyée avec succès']);
    } else {
        throw new Exception('Erreur lors de l\'insertion en base de données');
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Erreur lors de l\'envoi de la réponse: ' . $e->getMessage()]);
}