<?php

namespace App\Services;

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

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

        $query = Withdrawal::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('withdrawal_date', '>=', $params['start_date']);
        }
        if (! empty($params['end_date'])) {
            $query->where('withdrawal_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'] ?? 'withdrawal_date';
        $sortDir = $params['sort_dir'] ?? 'desc';
        $query->orderBy($sortBy, $sortDir);

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

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

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

        return Withdrawal::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): Withdrawal
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

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

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

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

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

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

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

            return $withdrawal->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) {
            $withdrawal = Withdrawal::query()
                ->where('tenant_id', $tenantId)
                ->findOrFail($id);

            $withdrawal->deleted_by = $userId;
            $withdrawal->save();
            $withdrawal->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 Withdrawal::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 = Withdrawal::query()
            ->where('tenant_id', $tenantId);

        // 날짜 범위 필터
        if (! empty($params['start_date'])) {
            $query->where('withdrawal_date', '>=', $params['start_date']);
        }
        if (! empty($params['end_date'])) {
            $query->where('withdrawal_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,
        ];
    }
}
