<?php

namespace App\Services;

use App\Models\Tenants\Bill;
use App\Models\Tenants\BillInstallment;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;

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

        $query = Bill::query()
            ->where('tenant_id', $tenantId)
            ->with(['client:id,name', 'bankAccount:id,bank_name,account_name', 'installments']);

        // 검색어 필터
        if (! empty($params['search'])) {
            $search = $params['search'];
            $query->where(function ($q) use ($search) {
                $q->where('bill_number', 'like', "%{$search}%")
                    ->orWhere('client_name', 'like', "%{$search}%")
                    ->orWhere('note', 'like', "%{$search}%")
                    ->orWhereHas('client', function ($q) use ($search) {
                        $q->where('name', 'like', "%{$search}%");
                    });
            });
        }

        // 어음 구분 필터 (received/issued)
        if (! empty($params['bill_type'])) {
            $query->where('bill_type', $params['bill_type']);
        }

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

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

        // 증권종류 필터
        if (! empty($params['instrument_type'])) {
            $query->where('instrument_type', $params['instrument_type']);
        }

        // 매체 필터
        if (! empty($params['medium'])) {
            $query->where('medium', $params['medium']);
        }

        // 전자어음 필터
        if (isset($params['is_electronic']) && $params['is_electronic'] !== '') {
            $query->where('is_electronic', (bool) $params['is_electronic']);
        }

        // 발행일 범위 필터
        if (! empty($params['issue_start_date'])) {
            $query->where('issue_date', '>=', $params['issue_start_date']);
        }
        if (! empty($params['issue_end_date'])) {
            $query->where('issue_date', '<=', $params['issue_end_date']);
        }

        // 만기일 범위 필터
        if (! empty($params['maturity_start_date'])) {
            $query->where('maturity_date', '>=', $params['maturity_start_date']);
        }
        if (! empty($params['maturity_end_date'])) {
            $query->where('maturity_date', '<=', $params['maturity_end_date']);
        }

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

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

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

    /**
     * 어음 상세 조회
     */
    public function show(int $id): Bill
    {
        $tenantId = $this->tenantId();

        return Bill::query()
            ->where('tenant_id', $tenantId)
            ->with(['client:id,name', 'bankAccount:id,bank_name,account_name', 'installments', 'creator:id,name'])
            ->findOrFail($id);
    }

    /**
     * 어음 등록
     */
    public function store(array $data): Bill
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        return DB::transaction(function () use ($data, $tenantId, $userId) {
            // 어음번호 자동 생성 (없을 경우)
            $billNumber = $data['bill_number'] ?? $this->generateBillNumber($tenantId);

            $bill = new Bill;
            $bill->tenant_id = $tenantId;
            $bill->bill_number = $billNumber;
            $bill->bill_type = $data['bill_type'];
            $bill->client_id = $data['client_id'] ?? null;
            $bill->client_name = $data['client_name'] ?? null;
            $bill->amount = $data['amount'];
            $bill->issue_date = $data['issue_date'];
            $bill->maturity_date = $data['maturity_date'] ?? null;
            $bill->status = $data['status'] ?? 'stored';
            $bill->reason = $data['reason'] ?? null;
            $bill->installment_count = $data['installment_count'] ?? 0;
            $bill->note = $data['note'] ?? null;
            $bill->is_electronic = $data['is_electronic'] ?? false;
            $bill->bank_account_id = $data['bank_account_id'] ?? null;

            // V8 확장 필드
            $this->assignV8Fields($bill, $data);

            $bill->created_by = $userId;
            $bill->updated_by = $userId;
            $bill->save();

            // 차수 관리 저장
            $this->syncInstallments($bill, $data['installments'] ?? [], $userId);

            return $bill->load(['client:id,name', 'bankAccount:id,bank_name,account_name', 'installments']);
        });
    }

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

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

            // 기존 필드
            if (isset($data['bill_number'])) {
                $bill->bill_number = $data['bill_number'];
            }
            if (isset($data['bill_type'])) {
                $bill->bill_type = $data['bill_type'];
            }
            if (array_key_exists('client_id', $data)) {
                $bill->client_id = $data['client_id'];
            }
            if (array_key_exists('client_name', $data)) {
                $bill->client_name = $data['client_name'];
            }
            if (isset($data['amount'])) {
                $bill->amount = $data['amount'];
            }
            if (isset($data['issue_date'])) {
                $bill->issue_date = $data['issue_date'];
            }
            if (array_key_exists('maturity_date', $data)) {
                $bill->maturity_date = $data['maturity_date'];
            }
            if (isset($data['status'])) {
                $bill->status = $data['status'];
            }
            if (array_key_exists('reason', $data)) {
                $bill->reason = $data['reason'];
            }
            if (array_key_exists('note', $data)) {
                $bill->note = $data['note'];
            }
            if (isset($data['is_electronic'])) {
                $bill->is_electronic = $data['is_electronic'];
            }
            if (array_key_exists('bank_account_id', $data)) {
                $bill->bank_account_id = $data['bank_account_id'];
            }

            // V8 확장 필드
            $this->assignV8Fields($bill, $data);

            $bill->updated_by = $userId;
            $bill->save();

            // 차수 관리 업데이트 (전체 교체)
            if (isset($data['installments'])) {
                $this->syncInstallments($bill, $data['installments'], $userId);
            }

            return $bill->fresh(['client:id,name', 'bankAccount:id,bank_name,account_name', 'installments']);
        });
    }

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

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

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

            return true;
        });
    }

    /**
     * 어음 상태 변경
     */
    public function updateStatus(int $id, string $status): Bill
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        $bill = Bill::query()
            ->where('tenant_id', $tenantId)
            ->findOrFail($id);

        $bill->status = $status;
        $bill->updated_by = $userId;
        $bill->save();

        return $bill->fresh(['client:id,name', 'bankAccount:id,bank_name,account_name', 'installments']);
    }

    /**
     * 어음 요약 (기간별 합계)
     */
    public function summary(array $params): array
    {
        $tenantId = $this->tenantId();

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

        // 어음 구분 필터
        if (! empty($params['bill_type'])) {
            $query->where('bill_type', $params['bill_type']);
        }

        // 발행일 범위 필터
        if (! empty($params['issue_start_date'])) {
            $query->where('issue_date', '>=', $params['issue_start_date']);
        }
        if (! empty($params['issue_end_date'])) {
            $query->where('issue_date', '<=', $params['issue_end_date']);
        }

        // 만기일 범위 필터
        if (! empty($params['maturity_start_date'])) {
            $query->where('maturity_date', '>=', $params['maturity_start_date']);
        }
        if (! empty($params['maturity_end_date'])) {
            $query->where('maturity_date', '<=', $params['maturity_end_date']);
        }

        // 전체 합계
        $total = (clone $query)->sum('amount');
        $count = (clone $query)->count();

        // 구분별 합계
        $byType = (clone $query)
            ->select('bill_type', DB::raw('SUM(amount) as total'), DB::raw('COUNT(*) as count'))
            ->groupBy('bill_type')
            ->get()
            ->keyBy('bill_type')
            ->toArray();

        // 상태별 합계
        $byStatus = (clone $query)
            ->select('status', DB::raw('SUM(amount) as total'), DB::raw('COUNT(*) as count'))
            ->groupBy('status')
            ->get()
            ->keyBy('status')
            ->toArray();

        // 만기 임박 (7일 이내)
        $maturityAlert = (clone $query)
            ->where('maturity_date', '>=', now()->toDateString())
            ->where('maturity_date', '<=', now()->addDays(7)->toDateString())
            ->whereNotIn('status', ['paymentComplete', 'collectionComplete', 'dishonored'])
            ->sum('amount');

        return [
            'total_amount' => (float) $total,
            'total_count' => $count,
            'by_type' => $byType,
            'by_status' => $byStatus,
            'maturity_alert_amount' => (float) $maturityAlert,
        ];
    }

    /**
     * 발행어음 대시보드 상세 조회 (CEO 대시보드 당월 예상 지출내역 me3 모달용)
     *
     * @return array{
     *     summary: array{current_month_total: float, previous_month_total: float, change_rate: float},
     *     monthly_trend: array<array{month: string, amount: float}>,
     *     by_vendor: array<array{vendor_name: string, amount: float, ratio: float}>,
     *     items: array<array{id: int, vendor_name: string, issue_date: string, maturity_date: string, amount: float, status: string, status_label: string}>
     * }
     */
    public function dashboardDetail(): array
    {
        $tenantId = $this->tenantId();

        // 현재 월 범위
        $currentMonthStart = now()->startOfMonth()->toDateString();
        $currentMonthEnd = now()->endOfMonth()->toDateString();

        // 전월 범위
        $previousMonthStart = now()->subMonth()->startOfMonth()->toDateString();
        $previousMonthEnd = now()->subMonth()->endOfMonth()->toDateString();

        // 1. 요약 정보 (발행어음 기준)
        $currentMonthTotal = Bill::query()
            ->where('tenant_id', $tenantId)
            ->where('bill_type', 'issued')
            ->whereBetween('issue_date', [$currentMonthStart, $currentMonthEnd])
            ->sum('amount');

        $previousMonthTotal = Bill::query()
            ->where('tenant_id', $tenantId)
            ->where('bill_type', 'issued')
            ->whereBetween('issue_date', [$previousMonthStart, $previousMonthEnd])
            ->sum('amount');

        $changeRate = $previousMonthTotal > 0
            ? round((($currentMonthTotal - $previousMonthTotal) / $previousMonthTotal) * 100, 1)
            : 0;

        // 2. 월별 추이 (최근 7개월)
        $monthlyTrend = [];
        for ($i = 6; $i >= 0; $i--) {
            $monthStart = now()->subMonths($i)->startOfMonth();
            $monthEnd = now()->subMonths($i)->endOfMonth();

            $amount = Bill::query()
                ->where('tenant_id', $tenantId)
                ->where('bill_type', 'issued')
                ->whereBetween('issue_date', [$monthStart->toDateString(), $monthEnd->toDateString()])
                ->sum('amount');

            $monthlyTrend[] = [
                'month' => $monthStart->format('Y-m'),
                'amount' => (float) $amount,
            ];
        }

        // 3. 거래처별 분포 (현재 월)
        $byVendorRaw = Bill::query()
            ->where('tenant_id', $tenantId)
            ->where('bill_type', 'issued')
            ->whereBetween('issue_date', [$currentMonthStart, $currentMonthEnd])
            ->select(
                DB::raw('COALESCE(client_name, (SELECT name FROM clients WHERE clients.id = bills.client_id)) as vendor_name'),
                DB::raw('SUM(amount) as amount')
            )
            ->groupBy('client_id', 'client_name')
            ->orderByDesc('amount')
            ->get();

        $totalAmount = $byVendorRaw->sum('amount');
        $byVendor = $byVendorRaw->map(function ($item) use ($totalAmount) {
            return [
                'vendor_name' => $item->vendor_name ?? '미지정',
                'amount' => (float) $item->amount,
                'ratio' => $totalAmount > 0 ? round(($item->amount / $totalAmount) * 100, 1) : 0,
            ];
        })->toArray();

        // 4. 발행어음 목록 (현재 월)
        $items = Bill::query()
            ->where('tenant_id', $tenantId)
            ->where('bill_type', 'issued')
            ->whereBetween('issue_date', [$currentMonthStart, $currentMonthEnd])
            ->with(['client:id,name'])
            ->orderBy('maturity_date', 'asc')
            ->get()
            ->map(function ($bill) {
                return [
                    'id' => $bill->id,
                    'vendor_name' => $bill->client?->name ?? $bill->client_name ?? '-',
                    'issue_date' => $bill->issue_date->format('Y-m-d'),
                    'maturity_date' => $bill->maturity_date->format('Y-m-d'),
                    'amount' => (float) $bill->amount,
                    'status' => $bill->status,
                    'status_label' => Bill::ISSUED_STATUSES[$bill->status] ?? $bill->status,
                ];
            })
            ->toArray();

        return [
            'summary' => [
                'current_month_total' => (float) $currentMonthTotal,
                'previous_month_total' => (float) $previousMonthTotal,
                'change_rate' => $changeRate,
            ],
            'monthly_trend' => $monthlyTrend,
            'by_vendor' => $byVendor,
            'items' => $items,
        ];
    }

    /**
     * V8 확장 필드를 Bill 모델에 할당
     */
    private function assignV8Fields(Bill $bill, array $data): void
    {
        $v8Fields = [
            'instrument_type', 'medium', 'bill_category',
            'electronic_bill_no', 'registration_org',
            'drawee', 'acceptance_status', 'acceptance_date',
            'acceptance_refusal_date', 'acceptance_refusal_reason',
            'endorsement', 'endorsement_order', 'storage_place', 'issuer_bank',
            'is_discounted', 'discount_date', 'discount_bank', 'discount_rate', 'discount_amount',
            'endorsement_date', 'endorsee', 'endorsement_reason',
            'collection_bank', 'collection_request_date', 'collection_fee',
            'collection_complete_date', 'collection_result', 'collection_deposit_date', 'collection_deposit_amount',
            'settlement_bank', 'payment_method', 'actual_payment_date',
            'payment_place', 'payment_place_detail',
            'renewal_date', 'renewal_new_bill_no', 'renewal_reason',
            'recourse_date', 'recourse_amount', 'recourse_target', 'recourse_reason',
            'buyback_date', 'buyback_amount', 'buyback_bank',
            'dishonored_date', 'dishonored_reason', 'has_protest', 'protest_date',
            'recourse_notice_date', 'recourse_notice_deadline',
            'is_split',
        ];

        foreach ($v8Fields as $field) {
            if (array_key_exists($field, $data)) {
                $bill->{$field} = $data[$field];
            }
        }
    }

    /**
     * 차수(이력) 동기화 — 기존 삭제 후 새로 생성
     */
    private function syncInstallments(Bill $bill, array $installments, int $userId): void
    {
        if (empty($installments)) {
            return;
        }

        // 기존 차수 삭제
        $bill->installments()->delete();

        // 새 차수 추가
        foreach ($installments as $installment) {
            BillInstallment::create([
                'bill_id' => $bill->id,
                'type' => $installment['type'] ?? 'other',
                'installment_date' => $installment['date'],
                'amount' => $installment['amount'],
                'counterparty' => $installment['counterparty'] ?? null,
                'note' => $installment['note'] ?? null,
                'created_by' => $userId,
            ]);
        }

        // 차수 카운트 업데이트
        $bill->installment_count = count($installments);
        $bill->save();
    }

    /**
     * 어음번호 자동 생성
     */
    private function generateBillNumber(int $tenantId): string
    {
        $prefix = date('Ym');
        $lastBill = Bill::query()
            ->where('tenant_id', $tenantId)
            ->where('bill_number', 'like', $prefix.'%')
            ->orderBy('bill_number', 'desc')
            ->first();

        if ($lastBill) {
            $lastNumber = (int) substr($lastBill->bill_number, strlen($prefix));
            $nextNumber = $lastNumber + 1;
        } else {
            $nextNumber = 1;
        }

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