<?php

namespace App\Services;

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

class CorporateCardService extends Service
{
    /**
     * 법인카드 목록 조회
     */
    public function index(array $params): LengthAwarePaginator
    {
        $tenantId = $this->tenantId();

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

        // 검색
        if (! empty($params['search'])) {
            $search = $params['search'];
            $query->where(function ($q) use ($search) {
                $q->where('card_name', 'like', "%{$search}%")
                    ->orWhere('card_company', 'like', "%{$search}%")
                    ->orWhere('card_number', 'like', "%{$search}%")
                    ->orWhere('card_holder_name', 'like', "%{$search}%")
                    ->orWhere('actual_user', 'like', "%{$search}%");
            });
        }

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

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

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

        return $query->paginate($params['per_page'] ?? 20);
    }

    /**
     * 법인카드 상세 조회
     */
    public function show(int $id): CorporateCard
    {
        return CorporateCard::query()
            ->where('tenant_id', $this->tenantId())
            ->findOrFail($id);
    }

    /**
     * 법인카드 등록
     */
    public function store(array $data): CorporateCard
    {
        $tenantId = $this->tenantId();

        return DB::transaction(function () use ($data, $tenantId) {
            return CorporateCard::create([
                'tenant_id' => $tenantId,
                'card_name' => $data['card_name'],
                'card_company' => $data['card_company'],
                'card_number' => $data['card_number'],
                'card_type' => $data['card_type'],
                'payment_day' => $data['payment_day'] ?? 15,
                'credit_limit' => $data['credit_limit'] ?? 0,
                'current_usage' => 0,
                'card_holder_name' => $data['card_holder_name'],
                'actual_user' => $data['actual_user'],
                'expiry_date' => $data['expiry_date'] ?? null,
                'cvc' => $data['cvc'] ?? null,
                'status' => $data['status'] ?? 'active',
                'memo' => $data['memo'] ?? null,
            ]);
        });
    }

    /**
     * 법인카드 수정
     */
    public function update(int $id, array $data): CorporateCard
    {
        return DB::transaction(function () use ($id, $data) {
            $card = CorporateCard::query()
                ->where('tenant_id', $this->tenantId())
                ->findOrFail($id);

            $card->fill([
                'card_name' => $data['card_name'] ?? $card->card_name,
                'card_company' => $data['card_company'] ?? $card->card_company,
                'card_number' => $data['card_number'] ?? $card->card_number,
                'card_type' => $data['card_type'] ?? $card->card_type,
                'payment_day' => $data['payment_day'] ?? $card->payment_day,
                'credit_limit' => $data['credit_limit'] ?? $card->credit_limit,
                'card_holder_name' => $data['card_holder_name'] ?? $card->card_holder_name,
                'actual_user' => $data['actual_user'] ?? $card->actual_user,
                'expiry_date' => $data['expiry_date'] ?? $card->expiry_date,
                'cvc' => $data['cvc'] ?? $card->cvc,
                'status' => $data['status'] ?? $card->status,
                'memo' => $data['memo'] ?? $card->memo,
            ]);

            $card->save();

            return $card->fresh();
        });
    }

    /**
     * 법인카드 삭제
     */
    public function destroy(int $id): bool
    {
        return DB::transaction(function () use ($id) {
            $card = CorporateCard::query()
                ->where('tenant_id', $this->tenantId())
                ->findOrFail($id);

            $card->delete();

            return true;
        });
    }

    /**
     * 법인카드 상태 토글 (사용/정지)
     */
    public function toggleStatus(int $id): CorporateCard
    {
        return DB::transaction(function () use ($id) {
            $card = CorporateCard::query()
                ->where('tenant_id', $this->tenantId())
                ->findOrFail($id);

            $card->toggleStatus();
            $card->save();

            return $card;
        });
    }

    /**
     * 활성 법인카드 목록 (셀렉트박스용)
     */
    public function getActiveCards(): array
    {
        return CorporateCard::query()
            ->where('tenant_id', $this->tenantId())
            ->where('status', 'active')
            ->orderBy('card_name')
            ->get(['id', 'card_name', 'card_company', 'card_number', 'card_type'])
            ->map(function ($card) {
                return [
                    'id' => $card->id,
                    'card_name' => $card->card_name,
                    'card_company' => $card->card_company,
                    'display_number' => $card->getMaskedCardNumber(),
                    'card_type' => $card->card_type,
                ];
            })
            ->toArray();
    }
}
