<?php
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'Gagal membuat tiket dari chat.', 'ticket_id' => null];

require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/session.php';
require_once __DIR__ . '/../../lib/Auth.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!Auth::isLoggedIn()) {
    http_response_code(401);
    $response['message'] = 'Sesi berakhir. Silakan login kembali.';
    echo json_encode($response);
    exit;
}
if (!isset($pdo) || !$pdo instanceof PDO) {
    http_response_code(500);
    error_log("PDO object not available in create_ticket_from_chat.php");
    $response['message'] = 'Koneksi database gagal.';
    echo json_encode($response);
    exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    $response['message'] = 'Metode request tidak valid.';
    echo json_encode($response);
    exit;
}

try {
    $userId = $_SESSION['user_id'];
    $subject = sanitize_input($_POST['subject'] ?? 'Permintaan dari Widget Chat');
    $message = sanitize_input($_POST['message'] ?? ''); 

    if (empty($subject)) {
        $subject = 'Permintaan dari Widget Chat'; 
    }
    if (empty($message)) {
        http_response_code(400);
        $response['message'] = 'Isi pesan tidak boleh kosong.';
        echo json_encode($response);
        exit;
    }

    $pdo->beginTransaction();

    $ticketId = 'TKT-' . strtoupper(substr(md5(uniqid(rand(), true)), 0, 10));

    $sqlInsertTicket = "INSERT INTO tickets (ticket_id, user_id, subject, message, status, priority, last_reply_by, is_read_user, is_read_admin, created_at, updated_at)
                        VALUES (:ticket_id, :user_id, :subject, :message, 'open', 'medium', 'user', 1, 0, NOW(), NOW())";
    $stmtInsertTicket = $pdo->prepare($sqlInsertTicket);
    $stmtInsertTicket->bindParam(':ticket_id', $ticketId);
    $stmtInsertTicket->bindParam(':user_id', $userId, PDO::PARAM_INT);
    $stmtInsertTicket->bindParam(':subject', $subject);
    $stmtInsertTicket->bindParam(':message', $message); 

    if (!$stmtInsertTicket->execute()) {
        throw new RuntimeException("Gagal menyimpan data tiket utama.");
    }
    $newTicketInternalId = $pdo->lastInsertId();
    $sqlInsertReply = "INSERT INTO ticket_replies (ticket_id, user_id, message, attachment_filename, created_at)
                       VALUES (:ticket_id, :user_id, :message, NULL, NOW())"; 
    $stmtInsertReply = $pdo->prepare($sqlInsertReply);
    $stmtInsertReply->bindParam(':ticket_id', $newTicketInternalId, PDO::PARAM_INT);
    $stmtInsertReply->bindParam(':user_id', $userId, PDO::PARAM_INT);
    $stmtInsertReply->bindParam(':message', $message);

    if (!$stmtInsertReply->execute()) {
        throw new RuntimeException("Gagal menyimpan pesan awal tiket.");
    }

    $pdo->commit();

    $response['success'] = true;
    $response['message'] = 'Tiket berhasil dibuat dari chat.';
    $response['ticket_id'] = $ticketId;

} catch (RuntimeException $e) {
    if ($pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("Create Ticket from Chat Runtime Error: " . $e->getMessage());
    $response['message'] = "Gagal memproses permintaan: " . $e->getMessage();
    http_response_code(500);
} catch (\PDOException $e) {
    if ($pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("Create Ticket from Chat DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan database saat memproses permintaan.";
    http_response_code(500);
} catch (\Throwable $e) {
    if ($pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("Create Ticket from Chat General Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan internal server.";
    if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_php'] = $e->getMessage(); }
    http_response_code(500);
}

echo json_encode($response);
exit;
