<?php

namespace App\Repositories;

use App\Models\Contract;
use App\Repositories\BaseRepository;

class ContractRepository extends BaseRepository
{
    public function __construct(Contract $model)
    {
        parent::__construct($model);
    }

    public function getAll(array $filters = [])
    {
        $query = $this->model->with(['jobPackage', 'contractor']);

        if (isset($filters['status'])) {
            $query->where('status', $filters['status']);
        }

        if (isset($filters['contractor_id'])) {
            $query->where('contractor_id', $filters['contractor_id']);
        }

        if (isset($filters['job_package_id'])) {
            $query->where('job_package_id', $filters['job_package_id']);
        }

        return $query->orderBy('created_at', 'desc')->paginate(15);
    }

    public function getByContractor(int $contractorId, array $filters = [])
    {
        $query = $this->model->where('contractor_id', $contractorId)
            ->with(['jobPackage']);

        if (isset($filters['status'])) {
            $query->where('status', $filters['status']);
        }

        return $query->orderBy('created_at', 'desc')->paginate(15);
    }

    public function generateContractNumber(): string
    {
        $year = date('Y');
        $last = $this->model->whereYear('created_at', $year)->count();
        $number = str_pad($last + 1, 4, '0', STR_PAD_LEFT);
        return "KTR/{$year}/{$number}";
    }
}