<?php
namespace App\Models;

use App\Core\DB;

class FileModel
{
    /** Get files in a folder (non-trashed) */
    public static function allInFolder(?int $folderId = null): array
    {
        if ($folderId === null) {
            $stmt = DB::get()->prepare("SELECT * FROM files WHERE folder_id IS NULL AND trashed_at IS NULL ORDER BY created_at DESC");
            $stmt->execute();
        } else {
            $stmt = DB::get()->prepare("SELECT * FROM files WHERE folder_id = ? AND trashed_at IS NULL ORDER BY created_at DESC");
            $stmt->execute([$folderId]);
        }
        return $stmt->fetchAll();
    }

    /** Get all trashed files */
    public static function allTrashed(): array
    {
        return DB::get()->query("SELECT * FROM files WHERE trashed_at IS NOT NULL ORDER BY trashed_at DESC")->fetchAll();
    }

    public static function findById(int $id): ?array
    {
        $stmt = DB::get()->prepare("SELECT * FROM files WHERE id = ? LIMIT 1");
        $stmt->execute([$id]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    public static function findByToken(string $token): ?array
    {
        $stmt = DB::get()->prepare("SELECT * FROM files WHERE shared_token = ? AND shared_enabled = 1 AND trashed_at IS NULL LIMIT 1");
        $stmt->execute([$token]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    public static function create(array $data): int
    {
        $stmt = DB::get()->prepare("INSERT INTO files (object_key, original_name, display_name, size_bytes, mime_type, folder_id) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $data['object_key'],
            $data['original_name'],
            $data['display_name'],
            $data['size_bytes'],
            $data['mime_type'],
            $data['folder_id'] ?? null,
        ]);
        return (int)DB::get()->lastInsertId();
    }

    public static function updateDisplayName(int $id, string $name): void
    {
        $stmt = DB::get()->prepare("UPDATE files SET display_name = ?, updated_at = datetime('now') WHERE id = ?");
        $stmt->execute([$name, $id]);
    }

    public static function updateShare(int $id, bool $enabled, ?string $token): void
    {
        $stmt = DB::get()->prepare("UPDATE files SET shared_enabled = ?, shared_token = ?, updated_at = datetime('now') WHERE id = ?");
        $stmt->execute([(int)$enabled, $token, $id]);
    }

    public static function moveToTrash(int $id): void
    {
        $stmt = DB::get()->prepare("UPDATE files SET trashed_at = datetime('now'), shared_enabled = 0, updated_at = datetime('now') WHERE id = ?");
        $stmt->execute([$id]);
    }

    public static function restoreFromTrash(int $id): void
    {
        $stmt = DB::get()->prepare("UPDATE files SET trashed_at = NULL, updated_at = datetime('now') WHERE id = ?");
        $stmt->execute([$id]);
    }

    public static function moveToFolder(int $id, ?int $folderId): void
    {
        $stmt = DB::get()->prepare("UPDATE files SET folder_id = ?, updated_at = datetime('now') WHERE id = ?");
        $stmt->execute([$folderId, $id]);
    }

    public static function delete(int $id): void
    {
        $stmt = DB::get()->prepare("DELETE FROM files WHERE id = ?");
        $stmt->execute([$id]);
    }

    public static function totalUsedBytes(): int
    {
        $row = DB::get()->query("SELECT COALESCE(SUM(size_bytes), 0) as total FROM files")->fetch();
        return (int)$row['total'];
    }

    public static function trashedCount(): int
    {
        $row = DB::get()->query("SELECT COUNT(*) as c FROM files WHERE trashed_at IS NOT NULL")->fetch();
        return (int)$row['c'];
    }
}
