<?php

namespace App\Services;

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

/**
 * 카드 거래 조회 서비스
 *
 * 카드 결제 내역 조회 및 계정과목 일괄 수정 기능 제공
 */
class CardTransactionService extends Service
{
    /**
     * 카드 거래 목록 조회
     *
     * @param  array{
     *     start_date?: string,
     *     end_date?: string,
     *     card_id?: int,
     *     search?: string,
     *     sort_by?: string,
     *     sort_dir?: string,
     *     per_page?: int,
     *     page?: int
     * }  $params
     */
    public function index(array $params = []): LengthAwarePaginator
    {
        $query = Withdrawal::query()
            ->where('payment_method', 'card')
            ->with(['card', 'card.assignedUser', 'creator']);

        // 날짜 필터
        if (! empty($params['start_date'])) {
            $query->where(function ($q) use ($params) {
                $q->whereDate('used_at', '>=', $params['start_date'])
                    ->orWhere(function ($q2) use ($params) {
                        $q2->whereNull('used_at')
                            ->whereDate('withdrawal_date', '>=', $params['start_date']);
                    });
            });
        }

        if (! empty($params['end_date'])) {
            $query->where(function ($q) use ($params) {
                $q->whereDate('used_at', '<=', $params['end_date'])
                    ->orWhere(function ($q2) use ($params) {
                        $q2->whereNull('used_at')
                            ->whereDate('withdrawal_date', '<=', $params['end_date']);
                    });
            });
        }

        // 카드 필터
        if (! empty($params['card_id'])) {
            $query->where('card_id', $params['card_id']);
        }

        // 검색 (카드번호, 가맹점명, 적요)
        if (! empty($params['search'])) {
            $search = $params['search'];
            $query->where(function ($q) use ($search) {
                $q->where('merchant_name', 'like', "%{$search}%")
                    ->orWhere('description', 'like', "%{$search}%")
                    ->orWhereHas('card', function ($cardQ) use ($search) {
                        $cardQ->where('card_name', 'like', "%{$search}%")
                            ->orWhere('card_company', 'like', "%{$search}%");
                    });
            });
        }

        // 정렬
        $sortBy = $params['sort_by'] ?? 'used_at';
        $sortDir = $params['sort_dir'] ?? 'desc';

        // 정렬 필드 매핑
        $sortableFields = [
            'used_at' => DB::raw('COALESCE(used_at, withdrawal_date)'),
            'amount' => 'amount',
            'merchant_name' => 'merchant_name',
            'created_at' => 'created_at',
        ];

        if (array_key_exists($sortBy, $sortableFields)) {
            $query->orderBy($sortableFields[$sortBy], $sortDir);
        } else {
            $query->orderBy(DB::raw('COALESCE(used_at, withdrawal_date)'), 'desc');
        }

        $perPage = $params['per_page'] ?? 20;

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

    /**
     * 카드 거래 요약 통계
     *
     * @param  array{start_date?: string, end_date?: string}  $params
     * @return array{
     *     previous_month_total: float,
     *     current_month_total: float,
     *     total_count: int,
     *     total_amount: float
     * }
     */
    public function summary(array $params = []): array
    {
        // 전월 기준일 계산
        $currentDate = now();
        $currentMonthStart = $currentDate->copy()->startOfMonth()->toDateString();
        $currentMonthEnd = $currentDate->copy()->endOfMonth()->toDateString();
        $previousMonthStart = $currentDate->copy()->subMonth()->startOfMonth()->toDateString();
        $previousMonthEnd = $currentDate->copy()->subMonth()->endOfMonth()->toDateString();

        // 전월 카드 사용액
        $previousMonthTotal = Withdrawal::query()
            ->where('payment_method', 'card')
            ->where(function ($q) use ($previousMonthStart, $previousMonthEnd) {
                $q->whereBetween(DB::raw('DATE(COALESCE(used_at, withdrawal_date))'), [$previousMonthStart, $previousMonthEnd]);
            })
            ->sum('amount');

        // 당월 카드 사용액
        $currentMonthTotal = Withdrawal::query()
            ->where('payment_method', 'card')
            ->where(function ($q) use ($currentMonthStart, $currentMonthEnd) {
                $q->whereBetween(DB::raw('DATE(COALESCE(used_at, withdrawal_date))'), [$currentMonthStart, $currentMonthEnd]);
            })
            ->sum('amount');

        // 조회 기간 내 총 건수/금액 (옵션)
        $periodQuery = Withdrawal::query()->where('payment_method', 'card');

        if (! empty($params['start_date'])) {
            $periodQuery->where(DB::raw('DATE(COALESCE(used_at, withdrawal_date))'), '>=', $params['start_date']);
        }
        if (! empty($params['end_date'])) {
            $periodQuery->where(DB::raw('DATE(COALESCE(used_at, withdrawal_date))'), '<=', $params['end_date']);
        }

        $totalCount = $periodQuery->count();
        $totalAmount = (clone $periodQuery)->sum('amount');

        return [
            'previous_month_total' => (float) $previousMonthTotal,
            'current_month_total' => (float) $currentMonthTotal,
            'total_count' => $totalCount,
            'total_amount' => (float) $totalAmount,
        ];
    }

    /**
     * 계정과목 일괄 수정
     *
     * @param  array<int>  $ids  거래 ID 배열
     * @param  string  $accountCode  계정과목 코드
     * @return int 수정된 건수
     */
    public function bulkUpdateAccountCode(array $ids, string $accountCode): int
    {
        return Withdrawal::query()
            ->whereIn('id', $ids)
            ->where('payment_method', 'card')
            ->update([
                'account_code' => $accountCode,
                'updated_by' => $this->apiUserId(),
            ]);
    }

    /**
     * 단일 카드 거래 조회
     */
    public function show(int $id): ?Withdrawal
    {
        return Withdrawal::query()
            ->where('payment_method', 'card')
            ->with(['card', 'card.assignedUser', 'creator'])
            ->find($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->card_id = $data['card_id'] ?? null;
            $withdrawal->used_at = $data['used_at'] ?? null;
            $withdrawal->withdrawal_date = isset($data['used_at']) ? date('Y-m-d', strtotime($data['used_at'])) : now()->toDateString();
            $withdrawal->merchant_name = $data['merchant_name'] ?? null;
            $withdrawal->amount = $data['amount'];
            $withdrawal->payment_method = 'card';
            $withdrawal->account_code = $data['account_code'] ?? null;
            $withdrawal->description = $data['description'] ?? null;
            $withdrawal->created_by = $userId;
            $withdrawal->updated_by = $userId;
            $withdrawal->save();

            return $withdrawal->load(['card', 'card.assignedUser', 'creator']);
        });
    }

    /**
     * 카드 거래 수정
     */
    public function update(int $id, array $data): Withdrawal
    {
        $userId = $this->apiUserId();

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

            if (isset($data['used_at'])) {
                $withdrawal->used_at = $data['used_at'];
                $withdrawal->withdrawal_date = date('Y-m-d', strtotime($data['used_at']));
            }
            if (array_key_exists('merchant_name', $data)) {
                $withdrawal->merchant_name = $data['merchant_name'];
            }
            if (isset($data['amount'])) {
                $withdrawal->amount = $data['amount'];
            }
            if (array_key_exists('account_code', $data)) {
                $withdrawal->account_code = $data['account_code'];
            }
            if (array_key_exists('description', $data)) {
                $withdrawal->description = $data['description'];
            }

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

            return $withdrawal->fresh(['card', 'card.assignedUser', 'creator']);
        });
    }

    /**
     * 카드 거래 삭제
     */
    public function destroy(int $id): bool
    {
        $userId = $this->apiUserId();

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

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

            return true;
        });
    }

    /**
     * 카드 거래 대시보드 데이터
     *
     * CEO 대시보드 카드/가지급금 관리 섹션(cm1) 및 당월 예상 지출내역 카드(me2) 모달용 상세 데이터 제공
     *
     * @return array{
     *     summary: array{
     *         current_month_total: float,
     *         previous_month_total: float,
     *         change_rate: float,
     *         current_month_count: int,
     *         unprocessed_count: int
     *     },
     *     monthly_trend: array<array{month: string, amount: float}>,
     *     user_ratio: array<array{user_name: string, amount: float, percentage: float}>,
     *     recent_transactions: array
     * }
     */
    public function dashboard(): array
    {
        $currentDate = now();

        // 당월/전월 기간 계산
        $currentMonthStart = $currentDate->copy()->startOfMonth()->toDateString();
        $currentMonthEnd = $currentDate->copy()->endOfMonth()->toDateString();
        $previousMonthStart = $currentDate->copy()->subMonth()->startOfMonth()->toDateString();
        $previousMonthEnd = $currentDate->copy()->subMonth()->endOfMonth()->toDateString();

        // 1. Summary 데이터
        $currentMonthTotal = $this->getMonthTotal($currentMonthStart, $currentMonthEnd);
        $previousMonthTotal = $this->getMonthTotal($previousMonthStart, $previousMonthEnd);

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

        // 당월 이용 건수
        $currentMonthCount = Withdrawal::query()
            ->where('payment_method', 'card')
            ->whereBetween(DB::raw('DATE(COALESCE(used_at, withdrawal_date))'), [$currentMonthStart, $currentMonthEnd])
            ->count();

        // 미정리 건수 (account_code가 없는 건)
        $unprocessedCount = Withdrawal::query()
            ->where('payment_method', 'card')
            ->whereNull('account_code')
            ->count();

        // 2. 최근 6개월 추이
        $monthlyTrend = $this->getMonthlyTrend(6);

        // 3. 사용자별 비율 (당월 기준)
        $userRatio = $this->getUserRatio($currentMonthStart, $currentMonthEnd);

        // 4. 최근 거래 10건
        $recentTransactions = $this->getRecentTransactions(10);

        return [
            'summary' => [
                'current_month_total' => (float) $currentMonthTotal,
                'previous_month_total' => (float) $previousMonthTotal,
                'change_rate' => $changeRate,
                'current_month_count' => $currentMonthCount,
                'unprocessed_count' => $unprocessedCount,
            ],
            'monthly_trend' => $monthlyTrend,
            'user_ratio' => $userRatio,
            'recent_transactions' => $recentTransactions,
        ];
    }

    /**
     * 특정 기간 카드 사용액 합계
     */
    private function getMonthTotal(string $startDate, string $endDate): float
    {
        return (float) Withdrawal::query()
            ->where('payment_method', 'card')
            ->whereBetween(DB::raw('DATE(COALESCE(used_at, withdrawal_date))'), [$startDate, $endDate])
            ->sum('amount');
    }

    /**
     * 최근 N개월 월별 추이
     *
     * @return array<array{month: string, amount: float}>
     */
    private function getMonthlyTrend(int $months): array
    {
        $result = [];
        $currentDate = now();

        for ($i = $months - 1; $i >= 0; $i--) {
            $targetDate = $currentDate->copy()->subMonths($i);
            $monthStart = $targetDate->copy()->startOfMonth()->toDateString();
            $monthEnd = $targetDate->copy()->endOfMonth()->toDateString();

            $amount = $this->getMonthTotal($monthStart, $monthEnd);

            $result[] = [
                'month' => $targetDate->format('Y-m'),
                'amount' => $amount,
            ];
        }

        return $result;
    }

    /**
     * 사용자별 카드 사용 비율
     *
     * @return array<array{user_name: string, amount: float, percentage: float}>
     */
    private function getUserRatio(string $startDate, string $endDate): array
    {
        $data = Withdrawal::query()
            ->select([
                'cards.assigned_user_id',
                DB::raw('COALESCE(users.name, "미지정") as user_name'),
                DB::raw('SUM(withdrawals.amount) as total_amount'),
            ])
            ->leftJoin('cards', 'withdrawals.card_id', '=', 'cards.id')
            ->leftJoin('users', 'cards.assigned_user_id', '=', 'users.id')
            ->where('withdrawals.payment_method', 'card')
            ->whereBetween(DB::raw('DATE(COALESCE(withdrawals.used_at, withdrawals.withdrawal_date))'), [$startDate, $endDate])
            ->groupBy('cards.assigned_user_id', 'users.name')
            ->orderByDesc('total_amount')
            ->get();

        $totalAmount = $data->sum('total_amount');

        return $data->map(function ($item) use ($totalAmount) {
            return [
                'user_name' => $item->user_name,
                'amount' => (float) $item->total_amount,
                'percentage' => $totalAmount > 0
                    ? round(($item->total_amount / $totalAmount) * 100, 1)
                    : 0,
            ];
        })->toArray();
    }

    /**
     * 최근 거래 목록
     */
    private function getRecentTransactions(int $limit): array
    {
        return Withdrawal::query()
            ->select([
                'withdrawals.id',
                'withdrawals.used_at',
                'withdrawals.withdrawal_date',
                'withdrawals.merchant_name',
                'withdrawals.amount',
                'withdrawals.account_code',
                'cards.card_name',
                DB::raw('COALESCE(users.name, "미지정") as user_name'),
            ])
            ->leftJoin('cards', 'withdrawals.card_id', '=', 'cards.id')
            ->leftJoin('users', 'cards.assigned_user_id', '=', 'users.id')
            ->where('withdrawals.payment_method', 'card')
            ->orderByDesc(DB::raw('COALESCE(withdrawals.used_at, withdrawals.withdrawal_date)'))
            ->limit($limit)
            ->get()
            ->map(function ($item) {
                return [
                    'id' => $item->id,
                    'card_name' => $item->card_name ?? '미지정',
                    'user_name' => $item->user_name,
                    'used_at' => $item->used_at?->format('Y-m-d H:i:s')
                        ?? $item->withdrawal_date?->format('Y-m-d'),
                    'merchant_name' => $item->merchant_name ?? '',
                    'amount' => (float) $item->amount,
                    'usage_type' => $item->account_code,
                ];
            })
            ->toArray();
    }
}
