<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Project;
use App\Models\Document;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function index()
    {
        // Estadísticas principales
        $stats = [
            'projects_count' => Project::count(),
            'documents_count' => Document::count(),
            'users_count' => User::count(),
            'storage_used' => $this->calculateStorageUsed(),
            'storage_limit' => 0,
            'storage_percentage' => 0,
        ];

        // Documentos recientes (últimos 7 días)
        $recentDocuments = Document::with(['project', 'currentVersion'])
            ->orderBy('created_at', 'desc')
            ->limit(5);

        // Actividad reciente
        $recentActivities = DB::table('activity_log')
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        $showSidebar = true; // Variable para mostrar el sidebar

        return view('dashboard', compact('stats', 'recentDocuments', 'recentActivities', 'showSidebar'));
    }

    private function calculateStorageUsed()
    {
        return Document::with('versions')
            ->get()
            ->sum(function($document) {
                return $document->versions->sum('size');
            });
    }

    public function storageUsage()
    {
        $total = $this->calculateStorageUsed();
        $limit = config('app.storage_limit', 1073741824); // 1GB por defecto
        
        return response()->json([
            'used' => $total,
            'limit' => $limit,
            'percentage' => ($total / $limit) * 100
        ]);
    }

    private function calculateStorage($projects)
    {
        // Adaptación de tu lógica existente + nueva propuesta
        return $projects->sum('storage_used') . ' GB';
    }
}