<?php

namespace App\Services;

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

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

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

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

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

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

        // 결제수단 필터
        if (! empty($params['payment_method'])) {
            $query->where('payment_method', $params['payment_method']);
        }

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

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

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

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

    /**
     * 입금 상세 조회
     */
    public function show(int $id): Deposit
    {
        $tenantId = $this->tenantId();

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

    /**
     * 입금 등록
     */
    public function store(array $data): Deposit
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        return DB::transaction(function () use ($data, $tenantId, $userId) {
            $deposit = new Deposit;
            $deposit->tenant_id = $tenantId;
            $deposit->deposit_date = $data['deposit_date'];
            $deposit->client_id = $data['client_id'] ?? null;
            $deposit->client_name = $data['client_name'] ?? null;
            $deposit->bank_account_id = $data['bank_account_id'] ?? null;
            $deposit->amount = $data['amount'];
            $deposit->payment_method = $data['payment_method'];
            $deposit->account_code = $data['account_code'] ?? null;
            $deposit->description = $data['description'] ?? null;
            $deposit->reference_type = $data['reference_type'] ?? null;
            $deposit->reference_id = $data['reference_id'] ?? null;
            $deposit->created_by = $userId;
            $deposit->updated_by = $userId;
            $deposit->save();

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

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

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

            if (isset($data['deposit_date'])) {
                $deposit->deposit_date = $data['deposit_date'];
            }
            if (array_key_exists('client_id', $data)) {
                $deposit->client_id = $data['client_id'];
            }
            if (array_key_exists('client_name', $data)) {
                $deposit->client_name = $data['client_name'];
            }
            if (array_key_exists('bank_account_id', $data)) {
                $deposit->bank_account_id = $data['bank_account_id'];
            }
            if (isset($data['amount'])) {
                $deposit->amount = $data['amount'];
            }
            if (isset($data['payment_method'])) {
                $deposit->payment_method = $data['payment_method'];
            }
            if (array_key_exists('account_code', $data)) {
                $deposit->account_code = $data['account_code'];
            }
            if (array_key_exists('description', $data)) {
                $deposit->description = $data['description'];
            }
            if (array_key_exists('reference_type', $data)) {
                $deposit->reference_type = $data['reference_type'];
            }
            if (array_key_exists('reference_id', $data)) {
                $deposit->reference_id = $data['reference_id'];
            }

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

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

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

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

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

            return true;
        });
    }

    /**
     * 계정과목 일괄 변경
     *
     * @param  array<int, int>  $ids  변경할 입금 ID 목록
     * @param  string  $accountCode  새 계정과목 코드
     * @return int 변경된 레코드 수
     */
    public function bulkUpdateAccountCode(array $ids, string $accountCode): int
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        return Deposit::query()
            ->where('tenant_id', $tenantId)
            ->whereIn('id', $ids)
            ->update([
                'account_code' => $accountCode,
                'updated_by' => $userId,
            ]);
    }

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

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

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

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

        // 결제수단 필터
        if (! empty($params['payment_method'])) {
            $query->where('payment_method', $params['payment_method']);
        }

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

        // 결제수단별 합계
        $byPaymentMethod = (clone $query)
            ->select('payment_method', DB::raw('SUM(amount) as total'), DB::raw('COUNT(*) as count'))
            ->groupBy('payment_method')
            ->get()
            ->keyBy('payment_method')
            ->toArray();

        return [
            'total_amount' => (float) $total,
            'total_count' => $count,
            'by_payment_method' => $byPaymentMethod,
        ];
    }
}
