<?php
declare(strict_types=1);
require_once dirname(__DIR__) . '/system/init.php'; header('Content-Type: application/json'); if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); exit(json_encode(['error' => 'Method not allowed.'])); } $raw = file_get_contents('php://input'); $input = json_decode($raw, true); if (!$input) { http_response_code(400); exit(json_encode(['error' => 'Invalid request.'])); } $csrf = $input['csrf'] ?? ''; if (!Auth::validateCsrf($csrf)) { http_response_code(403); exit(json_encode(['error' => 'Security token expired.'])); } $action = $input['action'] ?? ''; switch ($action) { case 'submit_ticket': if (!Auth::isLoggedIn()) { exit(json_encode(['error' => 'Please log in to submit a ticket.'])); } $user = Auth::user(); $subject = trim($input['subject'] ?? ''); $body = trim($input['body'] ?? ''); $urgency = $input['urgency'] ?? 'normal'; if ($body === '') { exit(json_encode(['error' => 'Message body is required.'])); } $validUrgency = ['low', 'normal', 'high', 'critical']; if (!in_array($urgency, $validUrgency, true)) $urgency = 'normal'; $ticketId = Database::insert( "INSERT INTO support_messages (user_id, subject, body, is_admin, urgency, status, created_at)              VALUES (:uid, :subj, :body, 0, :urg, 'open', NOW())", [ ':uid' => $user['id'], ':subj' => Crypt::encrypt($subject, Crypt::DOMAIN_LOG), ':body' => Crypt::encrypt($body, Crypt::DOMAIN_LOG), ':urg' => $urgency, ] ); Telemetry::logEvent('support', 'ticket.created', 'support', $ticketId); echo json_encode([ 'success' => true, 'ticket_id' => $ticketId, 'message' => 'Your message has been submitted.', 'csrf' => Auth::regenerateCsrf(), ]); break; case 'get_messages': if (!Auth::isLoggedIn()) { exit(json_encode(['error' => 'Please log in.'])); } $user = Auth::user(); $messages = Database::all( "SELECT id, subject, body, is_admin, is_read, urgency, status, created_at              FROM support_messages              WHERE user_id = :uid OR parent_id IN (SELECT id FROM support_messages WHERE user_id = :uid2)              ORDER BY created_at ASC", [':uid' => $user['id'], ':uid2' => $user['id']] ); foreach ($messages as &$msg) { $msg['subject'] = Crypt::render($msg['subject']); $msg['body'] = Crypt::render($msg['body']); } echo json_encode([ 'success' => true, 'messages' => $messages, 'csrf' => Auth::regenerateCsrf(), ]); break; case 'mark_read': if (!Auth::isLoggedIn()) { exit(json_encode(['error' => 'Please log in.'])); } $messageId = (int)($input['message_id'] ?? 0); $user = Auth::user(); Database::execute( "UPDATE support_messages SET is_read = 1 WHERE id = :id AND user_id = :uid", [':id' => $messageId, ':uid' => $user['id']] ); echo json_encode(['success' => true, 'csrf' => Auth::regenerateCsrf()]); break; default: echo json_encode(['error' => 'Unknown action.', 'csrf' => Auth::regenerateCsrf()]); }
