<?php
// Shared helpers for Rockview Connect Posts, Notifications and Communities.
ini_set('display_errors', '0');
ini_set('log_errors', '1');
header('Content-Type: application/json; charset=UTF-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Authorization, Content-Type, Accept');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/session_auth.php';

function connect_json(int $status, $body = null): void {
    http_response_code($status);
    if ($body !== null) {
        echo json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
    }
    exit;
}

function connect_body(): array {
    $raw = file_get_contents('php://input');
    if ($raw === false || trim($raw) === '') return [];
    $decoded = json_decode($raw, true);
    return is_array($decoded) ? $decoded : [];
}

function connect_text($value, int $max = 0): string {
    $text = trim((string)($value ?? ''));
    if ($max > 0 && strlen($text) > $max) {
        $text = substr($text, 0, $max);
    }
    return $text;
}

function connect_bool($value): bool {
    if (is_bool($value)) return $value;
    if (is_int($value)) return $value === 1;
    $text = strtolower(trim((string)$value));
    return in_array($text, ['1', 't', 'true', 'yes', 'y'], true);
}

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

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

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

function connect_upload_root(): string {
    return dirname(__DIR__) . '/uploads/connect_posts';
}

function connect_ensure_upload_dir(): string {
    $base = connect_upload_root();
    $dir = $base . '/' . date('Y') . '/' . date('m');
    if (!is_dir($dir) && !mkdir($dir, 0755, true) && !is_dir($dir)) {
        throw new RuntimeException('The server could not create the Connect media directory.');
    }
    return $dir;
}

function connect_relative_upload_path(string $absolutePath): string {
    $root = rtrim(dirname(__DIR__), '/\\') . DIRECTORY_SEPARATOR;
    $relative = str_replace('\\', '/', substr($absolutePath, strlen($root)));
    return ltrim($relative, '/');
}

function connect_ini_bytes(string $value): int {
    $value = trim($value);
    if ($value === '') return 0;
    $last = strtolower(substr($value, -1));
    $number = (float)$value;
    if ($last === 'g') $number *= 1024;
    if ($last === 'g' || $last === 'm') $number *= 1024;
    if ($last === 'g' || $last === 'm' || $last === 'k') $number *= 1024;
    return (int)$number;
}

function connect_assert_request_size(): void {
    $length = (int)($_SERVER['CONTENT_LENGTH'] ?? 0);
    $limit = connect_ini_bytes((string)ini_get('post_max_size'));
    if ($limit > 0 && $length > $limit) {
        connect_json(413, [
            'detail' => 'This upload is larger than the PHP post_max_size limit. Increase post_max_size and upload_max_filesize in php.ini, restart Apache, and try again.',
        ]);
    }
}

function connect_upload_error_message(int $code): string {
    switch ($code) {
        case UPLOAD_ERR_INI_SIZE:
            return 'The selected file is larger than the server upload_max_filesize setting.';
        case UPLOAD_ERR_FORM_SIZE:
            return 'The selected file is larger than the permitted form upload size.';
        case UPLOAD_ERR_PARTIAL:
            return 'The upload was interrupted before the file finished transferring.';
        case UPLOAD_ERR_NO_FILE:
            return 'No file was received by the server.';
        case UPLOAD_ERR_NO_TMP_DIR:
            return 'The PHP temporary upload folder is missing.';
        case UPLOAD_ERR_CANT_WRITE:
            return 'The server could not write the uploaded file to disk.';
        case UPLOAD_ERR_EXTENSION:
            return 'A PHP extension stopped the upload.';
        default:
            return 'The upload did not complete successfully.';
    }
}

function connect_store_upload(array $file, string $kind = 'post'): array {
    if (!isset($file['tmp_name'], $file['name'], $file['error'], $file['size'])) {
        throw new RuntimeException('The uploaded file is incomplete.');
    }

    $errorCode = (int)$file['error'];
    if ($errorCode !== UPLOAD_ERR_OK) {
        throw new RuntimeException(connect_upload_error_message($errorCode));
    }

    $tmp = (string)$file['tmp_name'];
    if (!is_uploaded_file($tmp)) {
        throw new RuntimeException('The uploaded file could not be verified by PHP.');
    }

    $size = (int)$file['size'];
    $originalName = connect_safe_file_name((string)$file['name']);
    $originalExt = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = strtolower((string)$finfo->file($tmp));

    $images = [
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/webp' => 'webp',
        'image/gif' => 'gif',
    ];
    $videos = [
        'video/mp4' => 'mp4',
        'video/webm' => 'webm',
        'video/quicktime' => 'mov',
        'video/x-m4v' => 'm4v',
    ];

    $mediaType = null;
    $extension = null;
    $maxBytes = 0;

    if (isset($images[$mime])) {
        $mediaType = 'image';
        $extension = $images[$mime];
        $maxBytes = $kind === 'comment' ? 8 * 1024 * 1024 : 10 * 1024 * 1024;
    } elseif ($kind !== 'comment' && isset($videos[$mime])) {
        $mediaType = 'video';
        $extension = $videos[$mime];
        $maxBytes = 50 * 1024 * 1024;
    } elseif (($mime === 'application/octet-stream' || $mime === 'binary/octet-stream') && $kind !== 'comment') {
        // Windows/PHP installations can report valid videos as octet-stream.
        $videoExtensions = ['mp4', 'webm', 'mov', 'm4v'];
        if (in_array($originalExt, $videoExtensions, true)) {
            $mediaType = 'video';
            $extension = $originalExt;
            $maxBytes = 50 * 1024 * 1024;
            $mime = $originalExt === 'webm' ? 'video/webm' : ($originalExt === 'mov' ? 'video/quicktime' : 'video/mp4');
        }
    }

    if ($mediaType === null) {
        throw new RuntimeException($kind === 'comment'
            ? 'Only JPEG, PNG, WebP or GIF pictures can be attached to comments.'
            : 'Only JPEG, PNG, WebP, GIF, MP4, WebM, MOV or M4V media can be attached to posts.');
    }

    if ($size <= 0 || $size > $maxBytes) {
        $limitMb = (int)round($maxBytes / 1024 / 1024);
        throw new RuntimeException("The selected {$mediaType} exceeds the {$limitMb} MB limit.");
    }

    $dir = connect_ensure_upload_dir();
    $storedName = sprintf(
        '%s_%s_%s.%s',
        $kind,
        date('Ymd_His'),
        bin2hex(random_bytes(8)),
        $extension
    );
    $target = $dir . '/' . $storedName;
    if (!move_uploaded_file($tmp, $target)) {
        throw new RuntimeException('The server could not save the uploaded media. Check the uploads/connect_posts folder permissions.');
    }

    return [
        'media_type' => $mediaType,
        'file_path' => connect_relative_upload_path($target),
        'absolute_path' => $target,
        'original_name' => $originalName,
        'mime_type' => $mime,
        'size_bytes' => $size,
    ];
}

function connect_normalize_files(string $field): array {
    if (!isset($_FILES[$field])) return [];
    $raw = $_FILES[$field];
    if (!is_array($raw['name'] ?? null)) return [$raw];

    $files = [];
    $count = count($raw['name']);
    for ($i = 0; $i < $count; $i++) {
        if (($raw['error'][$i] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) continue;
        $files[] = [
            'name' => $raw['name'][$i] ?? 'file',
            'type' => $raw['type'][$i] ?? '',
            'tmp_name' => $raw['tmp_name'][$i] ?? '',
            'error' => $raw['error'][$i] ?? UPLOAD_ERR_NO_FILE,
            'size' => $raw['size'][$i] ?? 0,
        ];
    }
    return $files;
}

function connect_remove_file(?string $relative): void {
    $relative = trim((string)$relative);
    if ($relative === '') return;
    $root = realpath(dirname(__DIR__));
    if (!$root) return;
    $candidate = dirname(__DIR__) . '/' . ltrim(str_replace('\\', '/', $relative), '/');
    $parent = realpath(dirname($candidate));
    if ($parent && strpos($parent, $root) === 0 && is_file($candidate)) {
        @unlink($candidate);
    }
}

function connect_notify(
    PDO $pdo,
    int $recipientId,
    string $recipientEmail,
    array $actor,
    string $type,
    string $title,
    string $body,
    ?int $postId = null,
    ?int $commentId = null,
    ?int $communityId = null,
    ?string $dedupeKey = null
): void {
    $actorId = (int)($actor['id'] ?? 0);
    if ($recipientId <= 0 || $recipientEmail === '' || ($actorId > 0 && $recipientId === $actorId)) return;

    $actorName = connect_text($actor['full_name'] ?? $actor['name'] ?? 'Rockview User', 255);
    $actorEmail = connect_text($actor['email'] ?? '', 255);
    $dedupeKey = connect_text($dedupeKey ?? '', 255);

    if ($dedupeKey !== '') {
        $existing = $pdo->prepare('SELECT id FROM connect_notifications WHERE recipient_id = ? AND dedupe_key = ? LIMIT 1');
        $existing->execute([$recipientId, $dedupeKey]);
        $existingId = (int)($existing->fetchColumn() ?: 0);
        if ($existingId > 0) {
            $update = $pdo->prepare("UPDATE connect_notifications
                                    SET actor_id = ?, actor_name = ?, actor_email = ?, type = ?, title = ?, body = ?,
                                        post_id = ?, comment_id = ?, community_id = ?, is_read = FALSE, created_at = CURRENT_TIMESTAMP
                                    WHERE id = ?");
            $update->execute([
                $actorId > 0 ? $actorId : null,
                $actorName,
                $actorEmail !== '' ? $actorEmail : null,
                $type,
                $title,
                $body,
                $postId,
                $commentId,
                $communityId,
                $existingId,
            ]);
            return;
        }
    }

    $insert = $pdo->prepare("INSERT INTO connect_notifications
        (recipient_id, recipient_email, actor_id, actor_name, actor_email, type, title, body, post_id, comment_id, community_id, dedupe_key)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $insert->execute([
        $recipientId,
        $recipientEmail,
        $actorId > 0 ? $actorId : null,
        $actorName,
        $actorEmail !== '' ? $actorEmail : null,
        $type,
        $title,
        $body,
        $postId,
        $commentId,
        $communityId,
        $dedupeKey !== '' ? $dedupeKey : null,
    ]);
}

function connect_delete_notification_by_key(PDO $pdo, int $recipientId, string $dedupeKey): void {
    if ($recipientId <= 0 || trim($dedupeKey) === '') return;
    $stmt = $pdo->prepare('DELETE FROM connect_notifications WHERE recipient_id = ? AND dedupe_key = ?');
    $stmt->execute([$recipientId, $dedupeKey]);
}

function connect_init_schema(PDO $pdo): void {
    $pdo->exec("CREATE TABLE IF NOT EXISTS connect_posts (
        id BIGSERIAL PRIMARY KEY,
        author_id BIGINT NULL,
        author_name VARCHAR(255) NOT NULL,
        author_email VARCHAR(255) NOT NULL,
        author_profile_picture TEXT NULL,
        campus VARCHAR(255) NULL,
        content TEXT NOT NULL DEFAULT '',
        tagged_name VARCHAR(255) NULL,
        location VARCHAR(255) NULL,
        visibility VARCHAR(40) NOT NULL DEFAULT 'public',
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS connect_post_media (
        id BIGSERIAL PRIMARY KEY,
        post_id BIGINT NOT NULL REFERENCES connect_posts(id) ON DELETE CASCADE,
        media_type VARCHAR(20) NOT NULL,
        file_path TEXT NOT NULL,
        original_name VARCHAR(255) NULL,
        mime_type VARCHAR(120) NULL,
        size_bytes BIGINT NOT NULL DEFAULT 0,
        sort_order INT NOT NULL DEFAULT 0,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS connect_post_likes (
        post_id BIGINT NOT NULL REFERENCES connect_posts(id) ON DELETE CASCADE,
        user_id BIGINT NOT NULL,
        user_email VARCHAR(255) NOT NULL,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (post_id, user_id)
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS connect_post_comments (
        id BIGSERIAL PRIMARY KEY,
        post_id BIGINT NOT NULL REFERENCES connect_posts(id) ON DELETE CASCADE,
        parent_id BIGINT NULL REFERENCES connect_post_comments(id) ON DELETE CASCADE,
        author_id BIGINT NULL,
        author_name VARCHAR(255) NOT NULL,
        author_email VARCHAR(255) NOT NULL,
        author_profile_picture TEXT NULL,
        content TEXT NOT NULL DEFAULT '',
        image_path TEXT NULL,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS connect_communities (
        id BIGSERIAL PRIMARY KEY,
        name VARCHAR(160) NOT NULL,
        description TEXT NOT NULL DEFAULT '',
        creator_id BIGINT NOT NULL,
        creator_name VARCHAR(255) NOT NULL,
        creator_email VARCHAR(255) NOT NULL,
        campus VARCHAR(255) NULL,
        is_active BOOLEAN NOT NULL DEFAULT TRUE,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS connect_community_members (
        community_id BIGINT NOT NULL REFERENCES connect_communities(id) ON DELETE CASCADE,
        user_id BIGINT NOT NULL,
        user_name VARCHAR(255) NOT NULL,
        user_email VARCHAR(255) NOT NULL,
        role VARCHAR(30) NOT NULL DEFAULT 'member',
        joined_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (community_id, user_id)
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS connect_notifications (
        id BIGSERIAL PRIMARY KEY,
        recipient_id BIGINT NOT NULL,
        recipient_email VARCHAR(255) NOT NULL,
        actor_id BIGINT NULL,
        actor_name VARCHAR(255) NOT NULL,
        actor_email VARCHAR(255) NULL,
        type VARCHAR(40) NOT NULL,
        title VARCHAR(180) NOT NULL,
        body TEXT NOT NULL DEFAULT '',
        post_id BIGINT NULL,
        comment_id BIGINT NULL,
        community_id BIGINT NULL,
        dedupe_key VARCHAR(255) NULL,
        is_read BOOLEAN NOT NULL DEFAULT FALSE,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
    )");

    // Safe upgrades for earlier versions of the module.
    $pdo->exec("ALTER TABLE connect_notifications ADD COLUMN IF NOT EXISTS dedupe_key VARCHAR(255) NULL");
    $pdo->exec("ALTER TABLE connect_notifications ADD COLUMN IF NOT EXISTS community_id BIGINT NULL");

    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_connect_posts_created_at ON connect_posts (created_at DESC)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_connect_post_comments_post ON connect_post_comments (post_id, created_at)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_connect_communities_created_at ON connect_communities (created_at DESC)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_connect_notifications_recipient ON connect_notifications (recipient_id, is_read, created_at DESC)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_connect_notifications_post ON connect_notifications (post_id)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_connect_notifications_dedupe ON connect_notifications (recipient_id, dedupe_key)");
}

connect_init_schema($pdo);
