<?php

namespace App\Services\Construction;

use App\Models\Construction\Contract;
use App\Models\Construction\HandoverReport;
use App\Models\Construction\HandoverReportItem;
use App\Models\Construction\HandoverReportManager;
use App\Services\Service;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;

class HandoverReportService extends Service
{
    /**
     * 인수인계보고서 목록 조회 (계약 완료건 기준)
     * 계약(완료) 테이블 LEFT JOIN 인수인계보고서
     */
    public function index(array $params): LengthAwarePaginator
    {
        $tenantId = $this->tenantId();

        // 계약 완료건 기준으로 조회 (LEFT JOIN handover_reports)
        $query = Contract::query()
            ->where('tenant_id', $tenantId)
            ->where('status', Contract::STATUS_COMPLETED)
            ->with('handoverReport');

        // 검색 필터 (계약 필드 기준)
        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['handover_status'])) {
            if ($params['handover_status'] === 'completed') {
                // 인수인계 완료 = 보고서 있음
                $query->whereHas('handoverReport');
            } elseif ($params['handover_status'] === 'pending') {
                // 인수인계 대기 = 보고서 없음
                $query->whereDoesntHave('handoverReport');
            }
        }

        // 거래처 필터
        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);
    }

    /**
     * 인수인계보고서 상세 조회 (계약 ID 기준)
     * 계약 정보 + 인수인계 보고서 관계 조회
     */
    public function show(int $contractId): Contract
    {
        $tenantId = $this->tenantId();

        return Contract::query()
            ->where('tenant_id', $tenantId)
            ->where('status', Contract::STATUS_COMPLETED)
            ->with(['handoverReport' => function ($query) {
                $query->with(['managers', 'items']);
            }, 'contractManager', 'constructionPm'])
            ->findOrFail($contractId);
    }

    /**
     * 인수인계보고서 등록
     */
    public function store(array $data): HandoverReport
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        return DB::transaction(function () use ($data, $tenantId, $userId) {
            // 메인 보고서 생성
            $report = HandoverReport::create([
                'tenant_id' => $tenantId,
                'report_number' => $data['report_number'],
                'contract_id' => $data['contract_id'] ?? null,
                'site_name' => $data['site_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_sites' => $data['total_sites'] ?? 0,
                'contract_amount' => $data['contract_amount'] ?? 0,
                'contract_date' => $data['contract_date'] ?? null,
                'contract_start_date' => $data['contract_start_date'] ?? null,
                'contract_end_date' => $data['contract_end_date'] ?? null,
                'completion_date' => $data['completion_date'] ?? null,
                'status' => $data['status'] ?? HandoverReport::STATUS_PENDING,
                'has_secondary_piping' => $data['has_secondary_piping'] ?? false,
                'secondary_piping_amount' => $data['secondary_piping_amount'] ?? 0,
                'secondary_piping_note' => $data['secondary_piping_note'] ?? null,
                'has_coating' => $data['has_coating'] ?? false,
                'coating_amount' => $data['coating_amount'] ?? 0,
                'coating_note' => $data['coating_note'] ?? null,
                'external_equipment_cost' => $data['external_equipment_cost'] ?? null,
                'special_notes' => $data['special_notes'] ?? null,
                'is_active' => $data['is_active'] ?? true,
                'created_by' => $userId,
                'updated_by' => $userId,
            ]);

            // 공사담당자 생성
            if (! empty($data['managers'])) {
                $this->syncManagers($report, $data['managers'], $tenantId, $userId);
            }

            // 계약 ITEM 생성
            if (! empty($data['items'])) {
                $this->syncItems($report, $data['items'], $tenantId, $userId);
            }

            return $report->load(['managers', 'items']);
        });
    }

    /**
     * 인수인계보고서 수정 (계약 ID 기준)
     * Contract ID로 해당 계약의 인수인계보고서를 찾아 수정
     * 보고서가 없으면 새로 생성
     */
    public function update(int $contractId, array $data): HandoverReport
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        return DB::transaction(function () use ($contractId, $data, $tenantId, $userId) {
            // 계약 확인 (완료된 계약만)
            $contract = Contract::query()
                ->where('tenant_id', $tenantId)
                ->where('status', Contract::STATUS_COMPLETED)
                ->findOrFail($contractId);

            // 해당 계약의 인수인계보고서 조회 (없으면 생성)
            $report = HandoverReport::query()
                ->where('tenant_id', $tenantId)
                ->where('contract_id', $contractId)
                ->first();

            if (! $report) {
                // 보고서가 없으면 새로 생성
                $report = new HandoverReport([
                    'tenant_id' => $tenantId,
                    'contract_id' => $contractId,
                    'created_by' => $userId,
                ]);
            }

            $report->fill([
                'report_number' => $data['report_number'] ?? $report->report_number,
                'contract_id' => $data['contract_id'] ?? $report->contract_id,
                'site_name' => $data['site_name'] ?? $report->site_name,
                'partner_id' => $data['partner_id'] ?? $report->partner_id,
                'partner_name' => $data['partner_name'] ?? $report->partner_name,
                'contract_manager_id' => $data['contract_manager_id'] ?? $report->contract_manager_id,
                'contract_manager_name' => $data['contract_manager_name'] ?? $report->contract_manager_name,
                'construction_pm_id' => $data['construction_pm_id'] ?? $report->construction_pm_id,
                'construction_pm_name' => $data['construction_pm_name'] ?? $report->construction_pm_name,
                'total_sites' => $data['total_sites'] ?? $report->total_sites,
                'contract_amount' => $data['contract_amount'] ?? $report->contract_amount,
                'contract_date' => $data['contract_date'] ?? $report->contract_date,
                'contract_start_date' => $data['contract_start_date'] ?? $report->contract_start_date,
                'contract_end_date' => $data['contract_end_date'] ?? $report->contract_end_date,
                'completion_date' => $data['completion_date'] ?? $report->completion_date,
                'status' => $data['status'] ?? $report->status,
                'has_secondary_piping' => $data['has_secondary_piping'] ?? $report->has_secondary_piping,
                'secondary_piping_amount' => $data['secondary_piping_amount'] ?? $report->secondary_piping_amount,
                'secondary_piping_note' => $data['secondary_piping_note'] ?? $report->secondary_piping_note,
                'has_coating' => $data['has_coating'] ?? $report->has_coating,
                'coating_amount' => $data['coating_amount'] ?? $report->coating_amount,
                'coating_note' => $data['coating_note'] ?? $report->coating_note,
                'external_equipment_cost' => $data['external_equipment_cost'] ?? $report->external_equipment_cost,
                'special_notes' => $data['special_notes'] ?? $report->special_notes,
                'is_active' => $data['is_active'] ?? $report->is_active,
                'updated_by' => $userId,
            ]);

            $report->save();

            // 공사담당자 동기화
            if (array_key_exists('managers', $data)) {
                $this->syncManagers($report, $data['managers'] ?? [], $tenantId, $userId);
            }

            // 계약 ITEM 동기화
            if (array_key_exists('items', $data)) {
                $this->syncItems($report, $data['items'] ?? [], $tenantId, $userId);
            }

            return $report->fresh(['managers', 'items']);
        });
    }

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

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

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

            return true;
        });
    }

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

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

            foreach ($reports as $report) {
                $report->deleted_by = $userId;
                $report->save();
                $report->delete();
            }

            return true;
        });
    }

    /**
     * 인수인계보고서 통계 조회 (계약 완료건 기준)
     */
    public function stats(array $params): array
    {
        $tenantId = $this->tenantId();

        // 계약 완료건 기준 조회
        $query = Contract::query()
            ->where('tenant_id', $tenantId)
            ->where('status', Contract::STATUS_COMPLETED);

        // 날짜 범위 필터
        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();

        // 인수인계 완료 (보고서 있음)
        $handoverCompletedCount = (clone $query)->whereHas('handoverReport')->count();

        // 인수인계 대기 (보고서 없음)
        $handoverPendingCount = (clone $query)->whereDoesntHave('handoverReport')->count();

        // 총 계약금액
        $totalAmount = (clone $query)->sum('contract_amount');

        // 총 현장 수
        $totalLocations = (clone $query)->sum('total_locations');

        return [
            'total_count' => $totalCount,
            'handover_completed_count' => $handoverCompletedCount,
            'handover_pending_count' => $handoverPendingCount,
            'total_amount' => (float) $totalAmount,
            'total_locations' => (int) $totalLocations,
        ];
    }

    /**
     * 공사담당자 동기화
     */
    private function syncManagers(HandoverReport $report, array $managers, int $tenantId, int $userId): void
    {
        // 기존 담당자 삭제
        $report->managers()->delete();

        // 새 담당자 생성
        foreach ($managers as $index => $manager) {
            HandoverReportManager::create([
                'tenant_id' => $tenantId,
                'handover_report_id' => $report->id,
                'name' => $manager['name'],
                'non_performance_reason' => $manager['non_performance_reason'] ?? null,
                'signature' => $manager['signature'] ?? null,
                'sort_order' => $index,
                'created_by' => $userId,
                'updated_by' => $userId,
            ]);
        }
    }

    /**
     * 계약 ITEM 동기화
     */
    private function syncItems(HandoverReport $report, array $items, int $tenantId, int $userId): void
    {
        // 기존 아이템 삭제
        $report->items()->delete();

        // 새 아이템 생성
        foreach ($items as $index => $item) {
            HandoverReportItem::create([
                'tenant_id' => $tenantId,
                'handover_report_id' => $report->id,
                'item_no' => $item['item_no'] ?? ($index + 1),
                'name' => $item['name'],
                'product' => $item['product'] ?? null,
                'quantity' => $item['quantity'] ?? 0,
                'remark' => $item['remark'] ?? null,
                'created_by' => $userId,
                'updated_by' => $userId,
            ]);
        }
    }
}
