<?php

namespace App\Services\Construction;

use App\Models\Bidding\Bidding;
use App\Models\Construction\Contract;
use App\Services\Service;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;

class ContractService extends Service
{
    /**
     * 계약 목록 조회
     */
    public function index(array $params): LengthAwarePaginator
    {
        $tenantId = $this->tenantId();

        $query = Contract::query()
            ->where('tenant_id', $tenantId);

        // 검색 필터
        if (! empty($params['search'])) {
            $search = $params['search'];
            $query->where(function ($q) use ($search) {
                $q->where('contract_code', 'like', "%{$search}%")
                    ->orWhere('project_name', 'like', "%{$search}%")
                    ->orWhere('partner_name', 'like', "%{$search}%");
            });
        }

        // 상태 필터
        if (! empty($params['status'])) {
            $query->where('status', $params['status']);
        }

        // 단계 필터
        if (! empty($params['stage'])) {
            $query->where('stage', $params['stage']);
        }

        // 거래처 필터
        if (! empty($params['partner_id'])) {
            $query->where('partner_id', $params['partner_id']);
        }

        // 계약담당자 필터
        if (! empty($params['contract_manager_id'])) {
            $query->where('contract_manager_id', $params['contract_manager_id']);
        }

        // 공사PM 필터
        if (! empty($params['construction_pm_id'])) {
            $query->where('construction_pm_id', $params['construction_pm_id']);
        }

        // 날짜 범위 필터
        if (! empty($params['start_date'])) {
            $query->where('contract_start_date', '>=', $params['start_date']);
        }
        if (! empty($params['end_date'])) {
            $query->where('contract_end_date', '<=', $params['end_date']);
        }

        // 활성화 상태 필터
        if (isset($params['is_active'])) {
            $query->where('is_active', $params['is_active']);
        }

        // 정렬
        $sortBy = $params['sort_by'] ?? 'created_at';
        $sortDir = $params['sort_dir'] ?? 'desc';
        $query->orderBy($sortBy, $sortDir);

        // 페이지네이션
        $perPage = $params['per_page'] ?? 20;

        return $query->paginate($perPage);
    }

    /**
     * 계약 상세 조회
     */
    public function show(int $id): Contract
    {
        $tenantId = $this->tenantId();

        return Contract::query()
            ->where('tenant_id', $tenantId)
            ->with(['contractManager', 'constructionPm', 'creator', 'updater'])
            ->findOrFail($id);
    }

    /**
     * 계약 등록
     */
    public function store(array $data): Contract
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        return DB::transaction(function () use ($data, $tenantId, $userId) {
            $contract = Contract::create([
                'tenant_id' => $tenantId,
                'contract_code' => $data['contract_code'],
                'project_name' => $data['project_name'],
                'partner_id' => $data['partner_id'] ?? null,
                'partner_name' => $data['partner_name'] ?? null,
                'contract_manager_id' => $data['contract_manager_id'] ?? null,
                'contract_manager_name' => $data['contract_manager_name'] ?? null,
                'construction_pm_id' => $data['construction_pm_id'] ?? null,
                'construction_pm_name' => $data['construction_pm_name'] ?? null,
                'total_locations' => $data['total_locations'] ?? 0,
                'contract_amount' => $data['contract_amount'] ?? 0,
                'contract_start_date' => $data['contract_start_date'] ?? null,
                'contract_end_date' => $data['contract_end_date'] ?? null,
                'status' => $data['status'] ?? Contract::STATUS_PENDING,
                'stage' => $data['stage'] ?? Contract::STAGE_ESTIMATE_SELECTED,
                'bidding_id' => $data['bidding_id'] ?? null,
                'bidding_code' => $data['bidding_code'] ?? null,
                'remarks' => $data['remarks'] ?? null,
                'is_active' => $data['is_active'] ?? true,
                'created_by' => $userId,
                'updated_by' => $userId,
            ]);

            return $contract;
        });
    }

    /**
     * 계약 수정
     */
    public function update(int $id, array $data): Contract
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        return DB::transaction(function () use ($id, $data, $tenantId, $userId) {
            $contract = Contract::query()
                ->where('tenant_id', $tenantId)
                ->findOrFail($id);

            $contract->fill([
                'contract_code' => $data['contract_code'] ?? $contract->contract_code,
                'project_name' => $data['project_name'] ?? $contract->project_name,
                'partner_id' => $data['partner_id'] ?? $contract->partner_id,
                'partner_name' => $data['partner_name'] ?? $contract->partner_name,
                'contract_manager_id' => $data['contract_manager_id'] ?? $contract->contract_manager_id,
                'contract_manager_name' => $data['contract_manager_name'] ?? $contract->contract_manager_name,
                'construction_pm_id' => $data['construction_pm_id'] ?? $contract->construction_pm_id,
                'construction_pm_name' => $data['construction_pm_name'] ?? $contract->construction_pm_name,
                'total_locations' => $data['total_locations'] ?? $contract->total_locations,
                'contract_amount' => $data['contract_amount'] ?? $contract->contract_amount,
                'contract_start_date' => $data['contract_start_date'] ?? $contract->contract_start_date,
                'contract_end_date' => $data['contract_end_date'] ?? $contract->contract_end_date,
                'status' => $data['status'] ?? $contract->status,
                'stage' => $data['stage'] ?? $contract->stage,
                'bidding_id' => $data['bidding_id'] ?? $contract->bidding_id,
                'bidding_code' => $data['bidding_code'] ?? $contract->bidding_code,
                'remarks' => $data['remarks'] ?? $contract->remarks,
                'is_active' => $data['is_active'] ?? $contract->is_active,
                'updated_by' => $userId,
            ]);

            $contract->save();

            return $contract->fresh();
        });
    }

    /**
     * 계약 삭제
     */
    public function destroy(int $id): bool
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        return DB::transaction(function () use ($id, $tenantId, $userId) {
            $contract = Contract::query()
                ->where('tenant_id', $tenantId)
                ->findOrFail($id);

            $contract->deleted_by = $userId;
            $contract->save();
            $contract->delete();

            return true;
        });
    }

    /**
     * 계약 일괄 삭제
     */
    public function bulkDestroy(array $ids): bool
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        return DB::transaction(function () use ($ids, $tenantId, $userId) {
            $contracts = Contract::query()
                ->where('tenant_id', $tenantId)
                ->whereIn('id', $ids)
                ->get();

            foreach ($contracts as $contract) {
                $contract->deleted_by = $userId;
                $contract->save();
                $contract->delete();
            }

            return true;
        });
    }

    /**
     * 계약 통계 조회
     */
    public function stats(array $params): array
    {
        $tenantId = $this->tenantId();

        $query = Contract::query()
            ->where('tenant_id', $tenantId);

        // 날짜 범위 필터
        if (! empty($params['start_date'])) {
            $query->where('contract_start_date', '>=', $params['start_date']);
        }
        if (! empty($params['end_date'])) {
            $query->where('contract_end_date', '<=', $params['end_date']);
        }

        $totalCount = (clone $query)->count();
        $pendingCount = (clone $query)->where('status', Contract::STATUS_PENDING)->count();
        $completedCount = (clone $query)->where('status', Contract::STATUS_COMPLETED)->count();
        $totalAmount = (clone $query)->sum('contract_amount');
        $totalLocations = (clone $query)->sum('total_locations');

        return [
            'total_count' => $totalCount,
            'pending_count' => $pendingCount,
            'completed_count' => $completedCount,
            'total_amount' => (float) $totalAmount,
            'total_locations' => (int) $totalLocations,
        ];
    }

    /**
     * 계약 단계별 카운트 조회
     */
    public function stageCounts(array $params): array
    {
        $tenantId = $this->tenantId();

        $query = Contract::query()
            ->where('tenant_id', $tenantId);

        // 날짜 범위 필터
        if (! empty($params['start_date'])) {
            $query->where('contract_start_date', '>=', $params['start_date']);
        }
        if (! empty($params['end_date'])) {
            $query->where('contract_end_date', '<=', $params['end_date']);
        }

        $stageCounts = (clone $query)
            ->select('stage', DB::raw('COUNT(*) as count'))
            ->groupBy('stage')
            ->pluck('count', 'stage')
            ->toArray();

        return [
            'estimate_selected' => $stageCounts[Contract::STAGE_ESTIMATE_SELECTED] ?? 0,
            'estimate_progress' => $stageCounts[Contract::STAGE_ESTIMATE_PROGRESS] ?? 0,
            'delivery' => $stageCounts[Contract::STAGE_DELIVERY] ?? 0,
            'installation' => $stageCounts[Contract::STAGE_INSTALLATION] ?? 0,
            'inspection' => $stageCounts[Contract::STAGE_INSPECTION] ?? 0,
            'other' => $stageCounts[Contract::STAGE_OTHER] ?? 0,
        ];
    }

    /**
     * 입찰에서 계약 생성 (낙찰 → 계약 전환)
     */
    public function storeFromBidding(int $biddingId, array $data = []): Contract
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        // 1. 입찰 조회
        $bidding = Bidding::where('tenant_id', $tenantId)->find($biddingId);

        if (! $bidding) {
            throw new NotFoundHttpException(__('error.bidding.not_found'));
        }

        // 2. 낙찰 상태인지 확인
        if (! $bidding->isConvertibleToContract()) {
            throw new UnprocessableEntityHttpException(
                __('error.contract.bidding_not_awarded')
            );
        }

        // 3. 이미 계약이 등록되었는지 확인
        $existingContract = Contract::where('tenant_id', $tenantId)
            ->where('bidding_id', $biddingId)
            ->first();

        if ($existingContract) {
            throw new ConflictHttpException(
                __('error.contract.already_registered', ['code' => $existingContract->contract_code])
            );
        }

        return DB::transaction(function () use ($bidding, $data, $tenantId, $userId) {
            // 계약번호 자동 생성
            $contractCode = $this->generateContractCode($tenantId);

            $contract = Contract::create([
                'tenant_id' => $tenantId,
                'contract_code' => $contractCode,
                'project_name' => $data['project_name'] ?? $bidding->project_name,
                'partner_id' => $data['partner_id'] ?? $bidding->client_id,
                'partner_name' => $data['partner_name'] ?? $bidding->client_name,
                'contract_manager_id' => $data['contract_manager_id'] ?? null,
                'contract_manager_name' => $data['contract_manager_name'] ?? null,
                'construction_pm_id' => $data['construction_pm_id'] ?? null,
                'construction_pm_name' => $data['construction_pm_name'] ?? null,
                'total_locations' => $data['total_locations'] ?? $bidding->total_count ?? 0,
                'contract_amount' => $data['contract_amount'] ?? $bidding->bidding_amount ?? 0,
                'contract_start_date' => $data['contract_start_date'] ?? $bidding->construction_start_date,
                'contract_end_date' => $data['contract_end_date'] ?? $bidding->construction_end_date,
                'status' => $data['status'] ?? Contract::STATUS_PENDING,
                'stage' => $data['stage'] ?? Contract::STAGE_ESTIMATE_SELECTED,
                'bidding_id' => $bidding->id,
                'bidding_code' => $bidding->bidding_code,
                'remarks' => $data['remarks'] ?? $bidding->remarks,
                'is_active' => $data['is_active'] ?? true,
                'created_by' => $userId,
                'updated_by' => $userId,
            ]);

            return $contract;
        });
    }

    /**
     * 계약번호 자동 생성 (CTR-YYYY-NNN)
     */
    private function generateContractCode(int $tenantId): string
    {
        $year = now()->year;
        $prefix = "CTR-{$year}-";

        // 올해 생성된 마지막 계약번호 조회
        $lastContract = Contract::where('tenant_id', $tenantId)
            ->where('contract_code', 'like', "{$prefix}%")
            ->orderBy('contract_code', 'desc')
            ->first();

        if ($lastContract) {
            // 마지막 번호에서 숫자 추출 후 +1
            $lastNumber = (int) substr($lastContract->contract_code, -3);
            $nextNumber = $lastNumber + 1;
        } else {
            $nextNumber = 1;
        }

        return $prefix.str_pad($nextNumber, 3, '0', STR_PAD_LEFT);
    }
}
