<?php
declare(strict_types=1);

require_once __DIR__ . '/session_auth.php';

function rvu_market_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_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);
    exit;
}

function rvu_market_input(): array {
    $raw = file_get_contents('php://input');
    if ($raw === false || trim($raw) === '') return [];
    $decoded = json_decode($raw, true);
    if (!is_array($decoded)) {
        rvu_market_json(['detail' => 'Invalid JSON request body.'], 400);
    }
    return $decoded;
}

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

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

function rvu_market_can_manage(array $user, ?int $sellerUserId): bool {
    return ($sellerUserId !== null && (int)$user['id'] === $sellerUserId)
        || rvu_market_is_admin($user['role'] ?? '');
}

function rvu_market_bool($value): bool {
    return $value === true || $value === 1 || $value === '1' || $value === 't' || $value === 'true';
}

function rvu_ensure_market_tables(PDO $pdo): void {
    $pdo->exec("CREATE TABLE IF NOT EXISTS campus_market_items (
        id BIGSERIAL PRIMARY KEY,
        seller_user_id BIGINT NULL,
        title VARCHAR(180) NOT NULL,
        description TEXT NOT NULL DEFAULT '',
        price NUMERIC(12,2) NOT NULL DEFAULT 0,
        category VARCHAR(80) NOT NULL DEFAULT 'Other',
        condition VARCHAR(80) NOT NULL DEFAULT 'Used - Good',
        quantity INTEGER NOT NULL DEFAULT 1,
        campus VARCHAR(180) NULL,
        location VARCHAR(220) NULL,
        seller_name VARCHAR(180) NULL,
        seller_phone VARCHAR(80) NULL,
        status VARCHAR(30) NOT NULL DEFAULT 'pending',
        report_reason TEXT NULL,
        legacy_image_url TEXT NULL,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
        approved_at TIMESTAMPTZ NULL,
        sold_at TIMESTAMPTZ NULL
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS campus_market_media (
        id BIGSERIAL PRIMARY KEY,
        item_id BIGINT NOT NULL REFERENCES campus_market_items(id) ON DELETE CASCADE,
        media_type VARCHAR(20) NOT NULL DEFAULT 'image',
        media_path TEXT NOT NULL,
        thumbnail_path TEXT NULL,
        file_size BIGINT NOT NULL DEFAULT 0,
        position INTEGER NOT NULL DEFAULT 0,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS campus_market_likes (
        id BIGSERIAL PRIMARY KEY,
        item_id BIGINT NOT NULL REFERENCES campus_market_items(id) ON DELETE CASCADE,
        user_id BIGINT NOT NULL,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
        CONSTRAINT campus_market_likes_unique UNIQUE (item_id, user_id)
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS campus_market_comments (
        id BIGSERIAL PRIMARY KEY,
        item_id BIGINT NOT NULL REFERENCES campus_market_items(id) ON DELETE CASCADE,
        user_id BIGINT NOT NULL,
        parent_comment_id BIGINT NULL REFERENCES campus_market_comments(id) ON DELETE CASCADE,
        comment TEXT NOT NULL,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS campus_market_comment_mentions (
        id BIGSERIAL PRIMARY KEY,
        comment_id BIGINT NOT NULL REFERENCES campus_market_comments(id) ON DELETE CASCADE,
        mentioned_user_id BIGINT NOT NULL,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
        CONSTRAINT campus_market_mentions_unique UNIQUE (comment_id, mentioned_user_id)
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS campus_market_notifications (
        id BIGSERIAL PRIMARY KEY,
        recipient_user_id BIGINT NOT NULL,
        actor_user_id BIGINT NULL,
        item_id BIGINT NULL REFERENCES campus_market_items(id) ON DELETE CASCADE,
        comment_id BIGINT NULL REFERENCES campus_market_comments(id) ON DELETE CASCADE,
        type VARCHAR(40) NOT NULL DEFAULT 'general',
        title VARCHAR(180) NOT NULL,
        message VARCHAR(280) NOT NULL DEFAULT '',
        is_read BOOLEAN NOT NULL DEFAULT FALSE,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS campus_market_inquiries (
        id BIGSERIAL PRIMARY KEY,
        item_id BIGINT NOT NULL REFERENCES campus_market_items(id) ON DELETE CASCADE,
        buyer_user_id BIGINT NOT NULL,
        seller_user_id BIGINT NULL,
        message TEXT NOT NULL,
        status VARCHAR(30) NOT NULL DEFAULT 'new',
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS campus_market_reports (
        id BIGSERIAL PRIMARY KEY,
        item_id BIGINT NOT NULL REFERENCES campus_market_items(id) ON DELETE CASCADE,
        reporter_user_id BIGINT NOT NULL,
        reason TEXT NOT NULL,
        status VARCHAR(30) NOT NULL DEFAULT 'open',
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
    )");

    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_market_items_status_created ON campus_market_items(status, created_at DESC)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_market_items_seller ON campus_market_items(seller_user_id)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_market_items_category ON campus_market_items(category)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_market_items_campus ON campus_market_items(campus)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_market_media_item ON campus_market_media(item_id, position)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_market_comments_item ON campus_market_comments(item_id, created_at)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_market_notifications_user ON campus_market_notifications(recipient_user_id, is_read, created_at DESC)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_market_reports_item ON campus_market_reports(item_id, created_at DESC)");

    rvu_market_try_import_legacy($pdo);
}

function rvu_market_try_import_legacy(PDO $pdo): void {
    try {
        $targetCount = (int)$pdo->query('SELECT COUNT(*) FROM campus_market_items')->fetchColumn();
        if ($targetCount > 0) return;

        $candidates = ['marketplace', 'marketplace_items', 'market_items'];
        foreach ($candidates as $table) {
            $check = $pdo->prepare('SELECT to_regclass(?)');
            $check->execute(['public.' . $table]);
            if (!$check->fetchColumn()) continue;

            $colsStmt = $pdo->prepare("SELECT column_name FROM information_schema.columns WHERE table_schema='public' AND table_name=?");
            $colsStmt->execute([$table]);
            $columns = $colsStmt->fetchAll(PDO::FETCH_COLUMN) ?: [];
            if (!in_array('title', $columns, true)) continue;

            $col = static function(string $name, string $fallback) use ($columns): string {
                return in_array($name, $columns, true) ? '"' . $name . '"' : $fallback;
            };

            $title = $col('title', "'Untitled item'");
            $description = $col('description', "''");
            $price = $col('price', '0');
            $sellerName = $col('seller_name', "'Legacy seller'");
            $sellerPhone = $col('seller_phone', "''");
            $image = $col('image_url', "''");
            $reportReason = $col('report_reason', "''");
            $created = $col('created_at', 'CURRENT_TIMESTAMP');
            $statusExpr = in_array('status', $columns, true)
                ? "CASE
                    WHEN LOWER(COALESCE(status::text,'')) IN ('active','approved') THEN 'active'
                    WHEN LOWER(COALESCE(status::text,'')) = 'reported' THEN 'reported'
                    WHEN LOWER(COALESCE(status::text,'')) = 'pending' THEN 'pending'
                    WHEN LOWER(COALESCE(status::text,'')) = 'sold' THEN 'sold'
                    ELSE 'active'
                   END"
                : "'active'";

            $sql = "INSERT INTO campus_market_items
                (title, description, price, seller_name, seller_phone, status, report_reason, legacy_image_url, created_at, updated_at)
                SELECT
                    COALESCE({$title}::text, 'Untitled item'),
                    COALESCE({$description}::text, ''),
                    CASE WHEN {$price}::text ~ '^[0-9]+([.][0-9]+)?$' THEN {$price}::numeric ELSE 0 END,
                    COALESCE({$sellerName}::text, 'Legacy seller'),
                    COALESCE({$sellerPhone}::text, ''),
                    {$statusExpr},
                    NULLIF({$reportReason}::text, ''),
                    NULLIF({$image}::text, ''),
                    COALESCE({$created}::timestamptz, CURRENT_TIMESTAMP),
                    COALESCE({$created}::timestamptz, CURRENT_TIMESTAMP)
                FROM \"{$table}\"";
            $pdo->exec($sql);
            break;
        }
    } catch (Throwable $e) {
        // Legacy import is best effort only. New marketplace remains usable.
    }
}

function rvu_market_normalize_item(array $row): array {
    $row['id'] = (int)($row['id'] ?? 0);
    $row['seller_user_id'] = $row['seller_user_id'] !== null ? (int)$row['seller_user_id'] : null;
    $row['price'] = (float)($row['price'] ?? 0);
    $row['quantity'] = (int)($row['quantity'] ?? 1);
    $row['like_count'] = (int)($row['like_count'] ?? 0);
    $row['comment_count'] = (int)($row['comment_count'] ?? 0);
    $row['inquiry_count'] = (int)($row['inquiry_count'] ?? 0);
    $row['liked_by_me'] = rvu_market_bool($row['liked_by_me'] ?? false);
    if (isset($row['media']) && is_string($row['media'])) {
        $decoded = json_decode($row['media'], true);
        $row['media'] = is_array($decoded) ? $decoded : [];
    } elseif (!isset($row['media']) || !is_array($row['media'])) {
        $row['media'] = [];
    }
    return $row;
}

function rvu_market_item_select_sql(): string {
    return "SELECT
        i.id, i.seller_user_id, i.title, i.description, i.price, i.category, i.condition,
        i.quantity, i.campus, i.location, i.seller_name, i.seller_phone, i.status,
        i.report_reason, i.legacy_image_url AS image_url, i.created_at, i.updated_at, i.sold_at,
        COALESCE(u.full_name, i.seller_name, 'Rockview Member') AS seller_name,
        COALESCE(u.role, 'staff') AS seller_role,
        COALESCE(u.profile_picture, '') AS seller_profile_picture,
        (SELECT COUNT(*) FROM campus_market_likes l WHERE l.item_id = i.id) AS like_count,
        (SELECT COUNT(*) FROM campus_market_comments c WHERE c.item_id = i.id) AS comment_count,
        (SELECT COUNT(*) FROM campus_market_inquiries q WHERE q.item_id = i.id) AS inquiry_count,
        EXISTS(SELECT 1 FROM campus_market_likes ml WHERE ml.item_id = i.id AND ml.user_id = :viewer_id) AS liked_by_me,
        COALESCE((
            SELECT json_agg(json_build_object(
                'id', m.id,
                'type', m.media_type,
                'path', m.media_path,
                'thumbnail_path', m.thumbnail_path,
                'file_size', m.file_size
            ) ORDER BY m.position, m.id)
            FROM campus_market_media m WHERE m.item_id = i.id
        ), '[]'::json) AS media
      FROM campus_market_items i
      LEFT JOIN users u ON u.id = i.seller_user_id";
}

function rvu_market_fetch_item(PDO $pdo, int $itemId, int $viewerId): ?array {
    $sql = rvu_market_item_select_sql() . ' WHERE i.id = :item_id LIMIT 1';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([':viewer_id' => $viewerId, ':item_id' => $itemId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row ? rvu_market_normalize_item($row) : null;
}

function rvu_market_fetch_comment(PDO $pdo, int $commentId): ?array {
    $stmt = $pdo->prepare("SELECT
        c.id, c.item_id, c.user_id, c.parent_comment_id, c.comment, c.created_at,
        u.full_name AS author_name, u.role AS author_role,
        COALESCE(u.profile_picture, '') AS author_profile_picture
      FROM campus_market_comments c
      INNER JOIN users u ON u.id = c.user_id
      WHERE c.id = ? LIMIT 1");
    $stmt->execute([$commentId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$row) return null;
    $row['id'] = (int)$row['id'];
    $row['item_id'] = (int)$row['item_id'];
    $row['user_id'] = (int)$row['user_id'];
    $row['parent_comment_id'] = $row['parent_comment_id'] !== null ? (int)$row['parent_comment_id'] : null;
    return $row;
}

function rvu_market_create_notification(
    PDO $pdo,
    int $recipientUserId,
    ?int $actorUserId,
    ?int $itemId,
    ?int $commentId,
    string $type,
    string $title,
    string $message
): void {
    if ($recipientUserId <= 0) return;
    if ($actorUserId !== null && $recipientUserId === $actorUserId) return;

    $stmt = $pdo->prepare("INSERT INTO campus_market_notifications
        (recipient_user_id, actor_user_id, item_id, comment_id, type, title, message)
        VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $recipientUserId,
        $actorUserId,
        $itemId,
        $commentId,
        mb_substr($type, 0, 40),
        mb_substr($title, 0, 180),
        mb_substr($message, 0, 280),
    ]);
}

function rvu_market_remove_physical_media(array $mediaRows): void {
    $root = realpath(__DIR__ . '/..');
    if ($root === false) return;
    foreach ($mediaRows as $row) {
        foreach (['media_path', 'thumbnail_path'] as $key) {
            $relative = trim((string)($row[$key] ?? ''));
            if ($relative === '' || strpos($relative, '..') !== false) continue;
            $relative = ltrim(str_replace('\\', '/', $relative), '/');
            if (!str_starts_with($relative, 'uploads/market/')) continue;
            $file = $root . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relative);
            if (is_file($file)) @unlink($file);
        }
    }
}
