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

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.'; echo json_encode($response); exit; }
if (!isset($pdo) || !$pdo instanceof PDO) { http_response_code(500); error_log("PDO object not available in close_ticket.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'];
    $isAdmin = ($_SESSION['user_role'] === 'admin');
    $ticketIdParam = sanitize_input($_POST['ticket_id'] ?? '');

    if (empty($ticketIdParam)) { throw new InvalidArgumentException("ID Tiket tidak valid."); }

    $pdo->beginTransaction();

    $sqlTicket = "SELECT id, user_id, status FROM tickets WHERE ticket_id = :ticket_id LIMIT 1 FOR UPDATE";
    $stmtTicket = $pdo->prepare($sqlTicket);
    $stmtTicket->bindParam(':ticket_id', $ticketIdParam);
    $stmtTicket->execute();
    $ticket = $stmtTicket->fetch(PDO::FETCH_ASSOC);

    if (!$ticket) { throw new InvalidArgumentException("Tiket tidak ditemukan."); }
    if (!$isAdmin && $ticket['user_id'] != $userId) { throw new InvalidArgumentException("Anda tidak punya akses untuk menutup tiket ini."); }
    if ($ticket['status'] === 'closed') { throw new InvalidArgumentException("Tiket ini sudah ditutup."); }

    $sqlUpdateTicket = "UPDATE tickets SET status = 'closed', updated_at = NOW() WHERE id = :internal_ticket_id";
    $stmtUpdateTicket = $pdo->prepare($sqlUpdateTicket);
    $stmtUpdateTicket->bindParam(':internal_ticket_id', $ticket['id'], PDO::PARAM_INT);

    if (!$stmtUpdateTicket->execute()) {
        throw new RuntimeException("Gagal memperbarui status tiket menjadi ditutup.");
    }

    $pdo->commit();

    $response['success'] = true;
    $response['message'] = 'Tiket berhasil ditutup.';

} catch (InvalidArgumentException $e) {
    if ($pdo->inTransaction()) { $pdo->rollBack(); }
    http_response_code(400);
    $response['message'] = $e->getMessage();
} catch (RuntimeException $e) {
    if ($pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("Close Ticket Runtime Error: " . $e->getMessage());
    $response['message'] = "Gagal menutup tiket: " . $e->getMessage();
    http_response_code(500);
} catch (\PDOException $e) {
    if ($pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("Close Ticket DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan database saat menutup tiket.";
    http_response_code(500);
} catch (\Throwable $e) {
    if ($pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("Close Ticket 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;
?>
