<?php
namespace App\Http\Controllers;

use App\Models\Project;
use App\Services\LimitService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ProjectController extends Controller
{
    protected $limitService;

    public function __construct(LimitService $limitService)
    {
        $this->limitService = $limitService;
    }

    public function create()
    {
        $user = Auth::user();
        
        // ✅ شمارش سرورها و محاسبه IP ها
        $projects = Project::withCount('servers')
            ->with(['servers' => function($query) {
                $query->withCount('ips');
            }])
            ->where('user_id', $user->id)
            ->get();

        $projects->map(function ($p) {
            $p->servers_route = route('projects.servers', $p->id);
            $p->servers_count = $p->servers_count ?? 0;
            // ✅ جمع کردن تعداد IP های تمام سرورهای این پروژه
            $p->ips_count = $p->servers->sum('ips_count');
            return $p;
        });

        // بررسی توانایی ایجاد پروژه جدید
        $canCreateProject = $this->limitService->canCreateProject($user->id);
        $limits = $this->limitService->getLimits();
        $usage = $this->limitService->getUsage($user->id);

        return view('projects.create_project', compact('projects', 'canCreateProject', 'limits', 'usage'));
    }

    public function store(Request $request)
    {
        $user = Auth::user();

        // ✅ بررسی محدودیت پروژه
        if (!$this->limitService->canCreateProject($user->id)) {
            return response()->json([
                'status' => 'error',
                'message' => 'شما به حد محدودیت پروژه‌های مجاز رسیده‌اید (' . $this->limitService->getLimits()['projects'] . ')'
            ], 403);
        }

        $request->validate([
            'name' => 'required|string|max:255'
        ]);

        $project = Project::create([
            'name' => $request->name,
            'user_id' => $user->id,
        ]);

        $project->servers_count = 0;
        $project->ips_count = 0;
        $project->servers_route = route('projects.servers', $project->id);

        return response()->json([
            'status' => 'success',
            'message' => 'پروژه با موفقیت ایجاد شد',
            'project' => $project
        ]);
    }

    public function rename(Request $request)
    {
        $user = Auth::user();

        $request->validate([
            'id' => 'required|exists:projects,id',
            'name' => 'required|string|max:255',
        ]);

        $project = Project::where('id', $request->id)
            ->where('user_id', $user->id)
            ->firstOrFail();

        $project->name = $request->name;
        $project->save();

        $project->servers_route = route('projects.servers', $project->id);

        return response()->json([
            'status' => 'success',
            'message' => 'نام پروژه با موفقیت تغییر یافت',
            'project' => $project
        ]);
    }

    public function destroy(Request $request)
    {
        $user = Auth::user();

        $request->validate(['id' => 'required|exists:projects,id']);

        $project = Project::where('id', $request->id)
            ->where('user_id', $user->id)
            ->firstOrFail();

        $project->delete();

        return response()->json([
            'status' => 'success',
            'message' => 'پروژه با موفقیت حذف شد',
            'refresh' => true
        ]);
    }

    public function servers($id)
    {
        $user = Auth::user();

        $project = Project::with('servers')
            ->where('id', $id)
            ->where('user_id', $user->id)
            ->firstOrFail();

        return view('projects.servers', [
            'project' => $project,
            'servers' => $project->servers
        ]);
    }
}