<?php

namespace App\Services;

use App\Models\Contract;
use App\Interfaces\Services\ContractorServiceInterface;
use App\Interfaces\Repositories\ContractorRepositoryInterface;
use Illuminate\Support\Facades\Storage;

class ContractorService implements ContractorServiceInterface
{
    public function __construct(
        protected ContractorRepositoryInterface $contractorRepo
    ) {}

    public function getProfile(int $userId)
    {
        return $this->contractorRepo->findByUserId($userId);
    }

    public function updateBusiness(int $userId, array $data)
    {
        $contractor = $this->contractorRepo->findByUserId($userId);
        if (!$contractor) return null;
        $this->contractorRepo->update($contractor->id, $data);
        return $contractor->fresh();
    }

    public function updateLegal(int $userId, array $data)
    {
        $contractor = $this->contractorRepo->findByUserId($userId);
        if (!$contractor) return null;
        return $contractor->legal()->updateOrCreate(
            ['contractor_id' => $contractor->id],
            $data
        );
    }

    public function updateBank(int $userId, array $data)
    {
        $contractor = $this->contractorRepo->findByUserId($userId);
        if (!$contractor) return null;
        if (isset($data['is_primary']) && $data['is_primary']) {
            $contractor->bankAccounts()->update(['is_primary' => false]);
        }
        $data['is_verified'] = false;
        return $contractor->bankAccounts()->create($data);
    }

    public function updateDirectors(int $userId, array $data)
    {
        $contractor = $this->contractorRepo->findByUserId($userId);
        if (!$contractor) return null;
        $contractor->directors()->delete();
        $directors = [];
        foreach ($data['directors'] as $directorData) {
            $directors[] = $contractor->directors()->create($directorData);
        }
        return $directors;
    }

    public function uploadDocument(int $userId, $file, string $type)
    {
        $contractor = $this->contractorRepo->findByUserId($userId);
        if (!$contractor) return null;
        $path = $file->store('contractors/' . $contractor->id . '/documents', 'public');
        return $contractor->documents()->create([
            'type' => $type,
            'name' => $file->getClientOriginalName(),
            'file_url' => $path,
            'size' => $file->getSize(),
            'uploaded_by' => $userId,
        ]);
    }

    public function deleteDocument(int $userId, int $documentId)
    {
        $contractor = $this->contractorRepo->findByUserId($userId);
        if (!$contractor) return false;
        $document = $contractor->documents()->find($documentId);
        if (!$document) return false;
        Storage::disk('public')->delete($document->file_url);
        return $document->delete();
    }

    public function getStatistics(int $userId)
    {
        $contractor = $this->contractorRepo->findByUserId($userId);
        if (!$contractor) return null;
        return $this->contractorRepo->getStatistics($contractor->id);
    }

    public function getMyContracts(int $userId, array $filters = [])
    {
        $contractor = $this->contractorRepo->findByUserId($userId);
        if (!$contractor) return null;
        $query = Contract::where('contractor_id', $contractor->id)
            ->with(['jobPackage', 'contractor']);
        if (isset($filters['status'])) {
            $query->where('status', $filters['status']);
        }
        return $query->orderBy('created_at', 'desc')->paginate(15);
    }
}