<?php

namespace App\Repositories;

use App\Models\Contractor;
use App\Interfaces\Repositories\ContractorRepositoryInterface;

class ContractorRepository extends BaseRepository implements ContractorRepositoryInterface
{
    public function __construct(Contractor $model)
    {
        $this->model = $model;
    }

    public function findByUserId(int $userId)
    {
        return $this->model->where('user_id', $userId)->first();
    }

    public function findByOapStatus(string $status)
    {
        return $this->model->where('oap_status', $status)->get();
    }

    public function findActive(array $filters = [])
    {
        $query = $this->model->where('is_active', true);
        if (isset($filters['oap_status'])) $query->where('oap_status', $filters['oap_status']);
        if (isset($filters['province'])) $query->where('province', $filters['province']);
        return $query->paginate(15);
    }

    public function updateSKP(int $id, int $skpRemaining)
    {
        $contractor = $this->model->find($id);
        if ($contractor) {
            $contractor->skp_remaining = $skpRemaining;
            $contractor->save();
        }
        return $contractor;
    }

    public function getStatistics(int $id)
    {
        $contractor = $this->model->with(['contracts'])->find($id);
        if (!$contractor) return null;

        return [
            'total_contracts' => $contractor->contracts->count(),
            'completed_contracts' => $contractor->contracts->where('status', 'completed')->count(),
            'active_contracts' => $contractor->contracts->whereIn('status', ['signed', 'execution'])->count(),
            'rating_avg' => $contractor->rating_avg,
            'skp_remaining' => $contractor->skp_remaining,
            'is_blacklisted' => $contractor->is_blacklisted,
        ];
    }

    public function findBlacklisted()
    {
        return $this->model->where('is_blacklisted', true)->get();
    }
}