<?php
// Ticket Media — upload photos/files to a ticket, add comments
require_auth();
$u = current_user();
$method = $_SERVER['REQUEST_METHOD'];
$d = input();

// ── GET: fetch comments + media for a ticket ─────────────────────────────────
if ($method === 'GET') {
    require_permission('tickets.view');
    $tid = (int)($_GET['ticket_id'] ?? 0);
    if (!$tid) json_error('ticket_id required', 422);

    $comments = db()->prepare("
        SELECT tc.*, u.name AS author_name, u.role_id,
               r.label AS role_label
        FROM ticket_comments tc
        JOIN users u ON u.id = tc.user_id
        JOIN roles r ON r.id = u.role_id
        WHERE tc.ticket_id = ?
        ORDER BY tc.created_at ASC
    ");
    $comments->execute([$tid]);

    $media = db()->prepare("
        SELECT tm.*, u.name AS uploader_name
        FROM ticket_media tm
        JOIN users u ON u.id = tm.uploaded_by
        WHERE tm.ticket_id = ?
        ORDER BY tm.created_at DESC
    ");
    $media->execute([$tid]);

    json_ok(['comments' => $comments->fetchAll(), 'media' => $media->fetchAll()]);
}

csrf_check();

// ── POST: add comment or upload photo ────────────────────────────────────────
if ($method === 'POST') {
    require_permission('tickets.view');
    $tid = (int)($d['ticket_id'] ?? 0);
    if (!$tid) json_error('ticket_id required', 422);

    $action = $d['action'] ?? 'comment';

    // ── Upload photo/file ──────────────────────────────────────────────────
    if ($action === 'upload') {
        if (empty($_FILES['file'])) json_error('No file uploaded', 422);
        $file = $_FILES['file'];
        $allowed = ['image/jpeg','image/png','image/webp','image/gif','application/pdf','video/mp4','video/quicktime'];
        if (!in_array($file['type'], $allowed, true)) json_error('File type not allowed', 422);
        if ($file['size'] > 20 * 1024 * 1024) json_error('Max file size is 20MB', 422);

        $ext   = pathinfo($file['name'], PATHINFO_EXTENSION);
        $name  = 'ticket_' . $tid . '_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . strtolower($ext);
        $dir   = __DIR__ . '/../../uploads/tickets/';
        if (!is_dir($dir)) mkdir($dir, 0755, true);
        $dest  = $dir . $name;
        if (!move_uploaded_file($file['tmp_name'], $dest)) json_error('Upload failed', 500);

        $url = (defined('APP_URL') ? APP_URL : '') . '/uploads/tickets/' . $name;
        db()->prepare("INSERT INTO ticket_media (ticket_id, uploaded_by, filename, original_name, file_type, file_size, url, created_at) VALUES (?,?,?,?,?,?,?,NOW())")
           ->execute([$tid, $u['id'], $name, $file['name'], $file['type'], $file['size'], $url]);

        $mid = (int)db()->lastInsertId();

        // Auto-comment about the upload
        $caption = trim((string)($d['caption'] ?? ''));
        $commentText = "📎 Uploaded: **{$file['name']}**" . ($caption ? "\n{$caption}" : '');
        db()->prepare("INSERT INTO ticket_comments (ticket_id, user_id, body, created_at) VALUES (?,?,?,NOW())")
           ->execute([$tid, $u['id'], $commentText]);

        // Notify ticket manager/admin
        $ticket = db()->prepare('SELECT t.title, t.property_id, p.name AS prop FROM tickets t JOIN properties p ON p.id=t.property_id WHERE t.id=?');
        $ticket->execute([$tid]);
        $tk = $ticket->fetch();
        if ($tk) {
            hv4_notify_admins("📸 Photo uploaded on ticket #{$tid}", "{$u['name']} uploaded {$file['name']} on: {$tk['title']}", 'ticket', '../pages/tickets.html');
            hv4_notify_role('tickets.manage', "📸 Photo uploaded on ticket #{$tid}", "{$u['name']} uploaded {$file['name']} on: {$tk['title']}", 'ticket', '../pages/tickets.html');
        }
        hv4_emit_event('ticket.media_uploaded', ['ticket_id' => $tid, 'by' => $u['name'], 'file' => $file['name']], 'ticket', $tid);

        json_ok(['id' => $mid, 'url' => $url, 'filename' => $name, 'original_name' => $file['name'], 'file_type' => $file['type']], 'Uploaded');
    }

    // ── Add comment / report ───────────────────────────────────────────────
    if ($action === 'comment') {
        $body = trim((string)($d['body'] ?? ''));
        if (!$body) json_error('Comment body required', 422);
        $escalate = !empty($d['escalate']) ? 1 : 0;

        db()->prepare("INSERT INTO ticket_comments (ticket_id, user_id, body, escalated, created_at) VALUES (?,?,?,?,NOW())")
           ->execute([$tid, $u['id'], $body, $escalate]);
        $cid = (int)db()->lastInsertId();

        // Notify based on escalation level
        $ticket = db()->prepare('SELECT t.*, p.name AS prop FROM tickets t JOIN properties p ON p.id=t.property_id WHERE t.id=?');
        $ticket->execute([$tid]);
        $tk = $ticket->fetch();

        if ($tk) {
            $preview = mb_strimwidth($body, 0, 100, '…');
            $icon = $escalate ? '🚨' : '💬';
            if ($escalate) {
                // Escalated → goes to admin
                hv4_notify_admins("{$icon} Escalated report on ticket #{$tid}", "{$u['name']} escalated: {$preview}", 'ticket', '../pages/tickets.html');
                hv4_emit_event('ticket.escalated', ['ticket_id' => $tid, 'by' => $u['name']], 'ticket', $tid);
            } else {
                // Normal comment → notify ticket manager
                hv4_notify_role('tickets.manage', "{$icon} New comment on ticket #{$tid}", "{$u['name']}: {$preview}", 'ticket', '../pages/tickets.html');
            }
        }

        json_ok(['id' => $cid], 'Comment added');
    }

    json_error('Unknown action', 422);
}

json_error('Method not allowed', 405);
