<?php

namespace App\Livewire;

use App\Models\Contract;
use App\Models\Contractor;
use App\Models\ContractorDocument;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;

class ContractorDashboard extends Component
{
    public $totalContracts;
    public $activeContracts;
    public $completedContracts;
    public $draftContracts;
    public $profile;
    public $recentContracts = [];
    public $documentsCount;

    public function mount()
    {
        $user = Auth::user();
        $this->profile = Contractor::where('user_id', $user->id)->first();

        if ($this->profile) {
            $this->totalContracts = Contract::where('contractor_id', $this->profile->id)->count();
            $this->activeContracts = Contract::where('contractor_id', $this->profile->id)
                ->whereIn('status', ['signed', 'execution'])
                ->count();
            $this->completedContracts = Contract::where('contractor_id', $this->profile->id)
                ->where('status', 'completed')
                ->count();
            $this->draftContracts = Contract::where('contractor_id', $this->profile->id)
                ->where('status', 'draft')
                ->count();
            $this->documentsCount = ContractorDocument::where('contractor_id', $this->profile->id)->count();

            $this->recentContracts = Contract::where('contractor_id', $this->profile->id)
                ->with(['jobPackage'])
                ->orderBy('created_at', 'desc')
                ->limit(5)
                ->get()
                ->toArray();
        }
    }

    public function render()
    {
        return view('livewire.contractor-dashboard');
    }
}