<?php
declare(strict_types=1);

require_once __DIR__ . '/session_auth.php';

function rvu_support_json($payload, int $status = 200): void
{
    http_response_code($status);
    header('Content-Type: application/json; charset=UTF-8');
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');
    echo json_encode(
        $payload,
        JSON_UNESCAPED_SLASHES |
        JSON_UNESCAPED_UNICODE |
        JSON_INVALID_UTF8_SUBSTITUTE
    );
    exit;
}

function rvu_support_input(): array
{
    $raw = file_get_contents('php://input');
    if ($raw === false || trim($raw) === '') {
        return [];
    }
    $decoded = json_decode($raw, true);
    if (!is_array($decoded)) {
        rvu_support_json(['detail' => 'Supply a valid JSON object.'], 400);
    }
    return $decoded;
}

function rvu_support_require_user(PDO $pdo): array
{
    $user = rvu_current_user($pdo);
    if (!$user) {
        rvu_support_json([
            'detail' => 'Your session is invalid. Please sign in again.'
        ], 401);
    }
    return $user;
}

function rvu_support_is_admin(?string $role): bool
{
    $role = strtolower(trim((string)$role));
    return in_array($role, [
        'admin',
        'administrator',
        'superadmin',
        'super_admin',
        'super admin',
    ], true);
}

function rvu_support_clean_text($value, int $max = 0, bool $required = false): string
{
    if ($value === null) {
        if ($required) {
            rvu_support_json(['detail' => 'A required field is missing.'], 400);
        }
        return '';
    }
    if (!is_string($value) && !is_numeric($value)) {
        rvu_support_json(['detail' => 'A text field contains an invalid value.'], 400);
    }
    $text = trim((string)$value);
    if ($required && $text === '') {
        rvu_support_json(['detail' => 'A required field is empty.'], 400);
    }
    if ($max > 0 && strlen($text) > $max) {
        rvu_support_json(['detail' => 'A field exceeds the allowed length.'], 400);
    }
    return $text;
}

function rvu_support_ensure_tables(PDO $pdo): void
{
    $pdo->exec("CREATE TABLE IF NOT EXISTS staff_support_threads (
        id BIGSERIAL PRIMARY KEY,
        author_id BIGINT NOT NULL,
        title VARCHAR(180) NOT NULL,
        category VARCHAR(80) NOT NULL DEFAULT 'General Support',
        priority VARCHAR(20) NOT NULL DEFAULT 'Normal',
        campus VARCHAR(180) NULL,
        status VARCHAR(30) NOT NULL DEFAULT 'waiting_admin',
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
        resolved_at TIMESTAMPTZ NULL,
        staff_last_read_at TIMESTAMPTZ NULL,
        admin_last_read_at TIMESTAMPTZ NULL
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS staff_support_messages (
        id BIGSERIAL PRIMARY KEY,
        thread_id BIGINT NOT NULL REFERENCES staff_support_threads(id) ON DELETE CASCADE,
        sender_user_id BIGINT NOT NULL,
        sender_role VARCHAR(80) NULL,
        body TEXT NULL,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS staff_support_media (
        id BIGSERIAL PRIMARY KEY,
        message_id BIGINT NOT NULL REFERENCES staff_support_messages(id) ON DELETE CASCADE,
        media_type VARCHAR(20) NOT NULL DEFAULT 'file',
        file_path TEXT NOT NULL,
        thumbnail_path TEXT NULL,
        original_name VARCHAR(255) NULL,
        mime_type VARCHAR(160) NULL,
        size_bytes BIGINT NOT NULL DEFAULT 0,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
    )");

    // Keep migrations safe for earlier development copies.
    $pdo->exec("ALTER TABLE staff_support_threads ADD COLUMN IF NOT EXISTS author_id BIGINT");
    $pdo->exec("ALTER TABLE staff_support_threads ADD COLUMN IF NOT EXISTS category VARCHAR(80) DEFAULT 'General Support'");
    $pdo->exec("ALTER TABLE staff_support_threads ADD COLUMN IF NOT EXISTS priority VARCHAR(20) DEFAULT 'Normal'");
    $pdo->exec("ALTER TABLE staff_support_threads ADD COLUMN IF NOT EXISTS campus VARCHAR(180)");
    $pdo->exec("ALTER TABLE staff_support_threads ADD COLUMN IF NOT EXISTS status VARCHAR(30) DEFAULT 'waiting_admin'");
    $pdo->exec("ALTER TABLE staff_support_threads ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP");
    $pdo->exec("ALTER TABLE staff_support_threads ADD COLUMN IF NOT EXISTS resolved_at TIMESTAMPTZ NULL");
    $pdo->exec("ALTER TABLE staff_support_threads ADD COLUMN IF NOT EXISTS staff_last_read_at TIMESTAMPTZ NULL");
    $pdo->exec("ALTER TABLE staff_support_threads ADD COLUMN IF NOT EXISTS admin_last_read_at TIMESTAMPTZ NULL");

    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_staff_support_threads_author ON staff_support_threads(author_id, updated_at DESC)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_staff_support_threads_status ON staff_support_threads(status, updated_at DESC)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_staff_support_messages_thread ON staff_support_messages(thread_id, created_at, id)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_staff_support_media_message ON staff_support_media(message_id, id)");
}

function rvu_support_can_access(array $user, array $thread): bool
{
    if (rvu_support_is_admin($user['role'] ?? '')) {
        return true;
    }
    return (int)($thread['author_id'] ?? 0) === (int)($user['id'] ?? 0);
}

function rvu_support_fetch_thread_basic(PDO $pdo, int $threadId): ?array
{
    $stmt = $pdo->prepare('SELECT * FROM staff_support_threads WHERE id = ? LIMIT 1');
    $stmt->execute([$threadId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row ?: null;
}

function rvu_support_thread_row(PDO $pdo, int $threadId, array $viewer): ?array
{
    $isAdmin = rvu_support_is_admin($viewer['role'] ?? '');
    $readColumn = $isAdmin ? 'admin_last_read_at' : 'staff_last_read_at';

    $sql = "SELECT
        t.id,
        t.author_id,
        t.title,
        t.category,
        t.priority,
        t.campus,
        t.status,
        t.created_at,
        t.updated_at,
        t.resolved_at,
        u.full_name AS author_name,
        u.role AS author_role,
        u.profile_picture AS author_profile_picture,
        COALESCE((SELECT COUNT(*) FROM staff_support_messages m WHERE m.thread_id = t.id), 0) AS message_count,
        COALESCE((
            SELECT COUNT(*)
            FROM staff_support_media a
            INNER JOIN staff_support_messages m2 ON m2.id = a.message_id
            WHERE m2.thread_id = t.id
        ), 0) AS attachment_count,
        COALESCE((
            SELECT m3.body
            FROM staff_support_messages m3
            WHERE m3.thread_id = t.id
            ORDER BY m3.created_at DESC, m3.id DESC
            LIMIT 1
        ), '') AS last_message,
        COALESCE((
            SELECT u3.full_name
            FROM staff_support_messages m4
            LEFT JOIN users u3 ON u3.id = m4.sender_user_id
            WHERE m4.thread_id = t.id
            ORDER BY m4.created_at DESC, m4.id DESC
            LIMIT 1
        ), '') AS last_sender_name,
        (
            SELECT m5.created_at
            FROM staff_support_messages m5
            WHERE m5.thread_id = t.id
            ORDER BY m5.created_at DESC, m5.id DESC
            LIMIT 1
        ) AS last_message_at,
        COALESCE((
            SELECT COUNT(*)
            FROM staff_support_messages um
            WHERE um.thread_id = t.id
              AND um.sender_user_id <> ?
              AND um.created_at > COALESCE(t.$readColumn, TIMESTAMPTZ '1970-01-01 00:00:00+00')
        ), 0) AS unread_count
      FROM staff_support_threads t
      LEFT JOIN users u ON u.id = t.author_id
      WHERE t.id = ?
      LIMIT 1";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([(int)$viewer['id'], $threadId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$row) {
        return null;
    }
    $row['id'] = (int)$row['id'];
    $row['author_id'] = (int)$row['author_id'];
    $row['message_count'] = (int)$row['message_count'];
    $row['attachment_count'] = (int)$row['attachment_count'];
    $row['unread_count'] = (int)$row['unread_count'];
    return $row;
}

function rvu_support_message_row(PDO $pdo, int $messageId, array $viewer): ?array
{
    $sql = "SELECT
        m.id,
        m.thread_id,
        m.sender_user_id,
        m.sender_role,
        m.body,
        m.created_at,
        COALESCE(u.full_name, 'Rockview User') AS sender_name,
        COALESCE(u.profile_picture, '') AS sender_profile_picture,
        (m.sender_user_id = ?) AS sent_by_me,
        COALESCE((
            SELECT json_agg(
                json_build_object(
                    'id', a.id,
                    'message_id', a.message_id,
                    'media_type', a.media_type,
                    'path', a.file_path,
                    'thumbnail_path', a.thumbnail_path,
                    'original_name', a.original_name,
                    'mime_type', a.mime_type,
                    'size_bytes', a.size_bytes
                ) ORDER BY a.id
            )
            FROM staff_support_media a
            WHERE a.message_id = m.id
        ), '[]'::json) AS attachments
      FROM staff_support_messages m
      LEFT JOIN users u ON u.id = m.sender_user_id
      WHERE m.id = ?
      LIMIT 1";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([(int)$viewer['id'], $messageId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$row) {
        return null;
    }
    $row['id'] = (int)$row['id'];
    $row['thread_id'] = (int)$row['thread_id'];
    $row['sender_user_id'] = (int)$row['sender_user_id'];
    $row['sent_by_me'] = in_array($row['sent_by_me'], [true, 1, '1', 't', 'true'], true);
    if (is_string($row['attachments'])) {
        $decoded = json_decode($row['attachments'], true);
        $row['attachments'] = is_array($decoded) ? $decoded : [];
    }
    return $row;
}

function rvu_support_mark_read(PDO $pdo, int $threadId, array $viewer): void
{
    $column = rvu_support_is_admin($viewer['role'] ?? '')
        ? 'admin_last_read_at'
        : 'staff_last_read_at';
    $stmt = $pdo->prepare("UPDATE staff_support_threads SET $column = CURRENT_TIMESTAMP WHERE id = ?");
    $stmt->execute([$threadId]);
}

function rvu_support_safe_filename(string $name): string
{
    $name = str_replace(["\r", "\n", "\0"], '', $name);
    $name = basename(str_replace('\\', '/', $name));
    $name = preg_replace('/[^A-Za-z0-9._ -]+/', '_', $name) ?: 'attachment';
    return substr($name, 0, 180);
}

function rvu_support_upload_dir(): string
{
    $dir = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'support';
    if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
        throw new RuntimeException('Unable to create the support upload directory.');
    }
    return $dir;
}

function rvu_support_make_thumbnail(string $sourcePath, string $targetPath, string $mime): bool
{
    if (!function_exists('imagecreatetruecolor')) {
        return false;
    }

    $image = null;
    if ($mime === 'image/jpeg' && function_exists('imagecreatefromjpeg')) {
        $image = @imagecreatefromjpeg($sourcePath);
    } elseif ($mime === 'image/png' && function_exists('imagecreatefrompng')) {
        $image = @imagecreatefrompng($sourcePath);
    } elseif ($mime === 'image/webp' && function_exists('imagecreatefromwebp')) {
        $image = @imagecreatefromwebp($sourcePath);
    }

    if (!$image) {
        return false;
    }

    $width = imagesx($image);
    $height = imagesy($image);
    if ($width <= 0 || $height <= 0) {
        imagedestroy($image);
        return false;
    }

    $maxWidth = 900;
    $ratio = min(1, $maxWidth / $width);
    $newWidth = max(1, (int)round($width * $ratio));
    $newHeight = max(1, (int)round($height * $ratio));
    $thumb = imagecreatetruecolor($newWidth, $newHeight);

    if ($mime === 'image/png' || $mime === 'image/webp') {
        imagealphablending($thumb, false);
        imagesavealpha($thumb, true);
    }

    imagecopyresampled(
        $thumb,
        $image,
        0,
        0,
        0,
        0,
        $newWidth,
        $newHeight,
        $width,
        $height
    );

    $ok = false;
    if ($mime === 'image/jpeg') {
        $ok = imagejpeg($thumb, $targetPath, 78);
    } elseif ($mime === 'image/png') {
        $ok = imagepng($thumb, $targetPath, 6);
    } elseif ($mime === 'image/webp' && function_exists('imagewebp')) {
        $ok = imagewebp($thumb, $targetPath, 78);
    }

    imagedestroy($thumb);
    imagedestroy($image);
    return $ok;
}
