<?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['status'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Données manquantes']);
    exit;
}

$ticketId = intval($input['ticket_id']);
$status = $input['status'];
$userId = $_SESSION['user_id'];

$allowedStatuses = ['open', 'in_progress', 'resolved', 'closed'];

if (!in_array($status, $allowedStatuses)) {
    http_response_code(400);
    echo json_encode(['error' => 'Statut invalide']);
    exit;
}

try {
    $db1 = getDB1Connection();
    
    $ticketCheckQuery = "SELECT user_id, status FROM support_tickets WHERE id = ?";
    $stmt = $db1->prepare($ticketCheckQuery);
    $stmt->execute([$ticketId]);
    $ticket = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$ticket) {
        http_response_code(404);
        echo json_encode(['error' => 'Ticket non trouvé']);
        exit;
    }
    
    $updateQuery = "UPDATE support_tickets SET status = ?, updated_at = NOW() WHERE id = ?";
    $stmt = $db1->prepare($updateQuery);
    $result = $stmt->execute([$status, $ticketId]);
    
    if ($result) {
        $statusMessages = [
            'open' => 'ouvert',
            'in_progress' => 'en cours',
            'resolved' => 'résolu',
            'closed' => 'fermé'
        ];
        
        if ($ticket['user_id'] != $userId) {
            $notificationQuery = "INSERT INTO ticket_notifications (ticket_id, user_id, message, created_at) 
                                 VALUES (?, ?, ?, NOW())";
            $stmt = $db1->prepare($notificationQuery);
            $stmt->execute([
                $ticketId, 
                $ticket['user_id'], 
                "Le statut de votre ticket #" . $ticketId . " a été mis à jour : " . $statusMessages[$status]
            ]);
        }
        
        echo json_encode([
            'success' => true, 
            'message' => 'Statut mis à jour avec succès',
            'new_status' => $status
        ]);
    } else {
        throw new Exception('Erreur lors de la mise à jour du statut');
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Erreur lors de la mise à jour du statut: ' . $e->getMessage()]);
}