<?php
session_start();
require_once 'db.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require './vendor/autoload.php';

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

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

if (!isset($input['ticketId']) || !isset($input['message'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing required fields']);
    exit;
}

try {
    $db = getDB1Connection();
    
    // Check if ticket is already taken
    $checkTicketQuery = $db->prepare("
        SELECT tackby, taken_at 
        FROM support_tickets 
        WHERE id = ?
    ");
    $checkTicketQuery->execute([$input['ticketId']]);
    $ticketInfo = $checkTicketQuery->fetch(PDO::FETCH_ASSOC);
    
    // Start transaction
    $db->beginTransaction();
    
    // Enregistrement de la réponse
    $responseQuery = $db->prepare("
        INSERT INTO ticket_responses 
        (ticket_id, user_id, response, is_staff, created_at) 
        VALUES (?, ?, ?, 1, NOW())
    ");
    $responseQuery->execute([
        $input['ticketId'],
        $_SESSION['user_id'],
        $input['message']
    ]);
    
    // Mise à jour du ticket
    // Si le ticket n'est pas pris ou est pris par l'utilisateur actuel
    if (!$ticketInfo['tackby'] || $ticketInfo['tackby'] === $_SESSION['username']) {
        $updateTicketQuery = $db->prepare("
            UPDATE support_tickets 
            SET 
                updated_at = NOW(),
                tackby = ?,
                taken_at = CASE 
                    WHEN taken_at IS NULL THEN NOW()
                    ELSE taken_at
                END,
                status = CASE 
                    WHEN status = 'open' THEN 'in_progress'
                    ELSE status 
                END
            WHERE id = ?
        ");
        $updateTicketQuery->execute([$_SESSION['username'], $input['ticketId']]);
    }
    
    // Récupération des informations pour l'email
    $userQuery = $db->prepare("
        SELECT t.subject, u.email, u.username 
        FROM support_tickets t 
        JOIN utilisateurs u ON t.user_id = u.id 
        WHERE t.id = ?
    ");
    $userQuery->execute([$input['ticketId']]);
    $userInfo = $userQuery->fetch(PDO::FETCH_ASSOC);
    
    // Commit the transaction
    $db->commit();
    
    // Envoi de l'email
    if ($userInfo) {
        $mail = new PHPMailer(true);
        
        try {
            $mail->isSMTP();
            $mail->Host = 'web05.ouiheberg.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'no-reply@imators.systems';
            $mail->Password = 'imaors_management.346980*#@-onlyforcpanel;forchange';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port = 465;
            $mail->CharSet = 'UTF-8';
            
            $mail->setFrom('no-reply@imators.systems', 'Imators Support');
            $mail->addAddress($userInfo['email']);
            $mail->Subject = "Imators Support | Ticket Response #{$input['ticketId']}";
            $mail->isHTML(true);
            
            $mail->Body = "
                <p>Dear " . htmlspecialchars($userInfo['username']) . ",</p>
                <p>A support member has responded to your ticket. You can view the full conversation in your account.</p>
                <div style='background: #f5f5f5; padding: 15px; margin: 20px 0;'>
                    " . nl2br(htmlspecialchars($input['message'])) . "
                </div>
                <p>
                    <a href='https://idsma.imators.com/view_ticket.php?id={$input['ticketId']}' 
                       style='background: #4CAF50; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block;'>
                        View Full Ticket
                    </a>
                </p>
                <p style='color: #666; font-size: 12px; margin-top: 20px;'>
                    This is an automated message, please do not reply directly to this email.
                </p>";
            
            $mail->send();
        } catch (Exception $e) {
            error_log("Email sending failed: " . $e->getMessage());
        }
    }
    
    // Récupérer les informations mises à jour pour la réponse
    $updatedTicketQuery = $db->prepare("
        SELECT tackby, taken_at, status 
        FROM support_tickets 
        WHERE id = ?
    ");
    $updatedTicketQuery->execute([$input['ticketId']]);
    $updatedTicket = $updatedTicketQuery->fetch(PDO::FETCH_ASSOC);
    
    // Renvoyer la réponse avec toutes les informations nécessaires
    echo json_encode([
        'success' => true,
        'response' => [
            'id' => $db->lastInsertId(),
            'message' => $input['message'],
            'created_at' => date('Y-m-d H:i:s'),
            'username' => $_SESSION['username'],
            'is_staff' => 1,
            'user_id' => $_SESSION['user_id']
        ],
        'ticket' => [
            'tackby' => $updatedTicket['tackby'],
            'taken_at' => $updatedTicket['taken_at'],
            'status' => $updatedTicket['status']
        ]
    ]);

} catch (PDOException $e) {
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    error_log("Database error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Database error']);
} catch (Exception $e) {
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    error_log("Server error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
}