<?php

namespace App\Http\Controllers;

use App\Models\Finance\BankAccount;
use App\Models\Finance\CorporateCard;
use App\Models\Tenants\Tenant;
use App\Models\Tenants\TenantSetting;
use App\Services\ApprovalService;
use App\Services\HR\LeaveService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;

class ApprovalController extends Controller
{
    public function __construct(
        private readonly ApprovalService $service
    ) {}

    /**
     * 기안함
     */
    public function drafts(Request $request): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('approvals.drafts'));
        }

        return view('approvals.drafts');
    }

    /**
     * 기안 작성
     */
    public function create(Request $request): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('approvals.create'));
        }

        $forms = $this->service->getApprovalForms();
        $lines = $this->service->getApprovalLines();
        [$cards, $accounts] = $this->getCardAndAccountData();
        $employees = app(LeaveService::class)->getActiveEmployees();
        $tenantInfo = $this->getTenantInfo();

        return view('approvals.create', compact('forms', 'lines', 'cards', 'accounts', 'employees', 'tenantInfo'));
    }

    /**
     * 기안 수정
     */
    public function edit(Request $request, int $id): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('approvals.edit', $id));
        }

        $approval = $this->service->getApproval($id);

        if (! $approval->isEditable() || $approval->drafter_id !== auth()->id()) {
            abort(403, '수정할 수 없습니다.');
        }

        $forms = $this->service->getApprovalForms();
        $lines = $this->service->getApprovalLines();
        [$cards, $accounts] = $this->getCardAndAccountData();
        $employees = app(LeaveService::class)->getActiveEmployees();
        $tenantInfo = $this->getTenantInfo();

        return view('approvals.edit', compact('approval', 'forms', 'lines', 'cards', 'accounts', 'employees', 'tenantInfo'));
    }

    /**
     * 결재 상세
     */
    public function show(Request $request, int $id): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('approvals.show', $id));
        }

        $approval = $this->service->getApproval($id);

        return view('approvals.show', compact('approval'));
    }

    /**
     * 결재 대기함
     */
    public function pending(Request $request): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('approvals.pending'));
        }

        return view('approvals.pending');
    }

    /**
     * 참조함
     */
    public function references(Request $request): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('approvals.references'));
        }

        return view('approvals.references');
    }

    /**
     * 완료함
     */
    public function completed(Request $request): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('approvals.completed'));
        }

        return view('approvals.completed');
    }

    private function getTenantInfo(): array
    {
        $tenantId = session('selected_tenant_id');
        $tenant = Tenant::find($tenantId);

        if (! $tenant) {
            return [];
        }

        $displaySetting = TenantSetting::withoutGlobalScopes()
            ->where('tenant_id', $tenantId)
            ->where('setting_group', 'company')
            ->where('setting_key', 'display_company_name')
            ->first();
        $displayName = $displaySetting?->setting_value ?? '';

        return [
            'company_name' => ! empty($displayName) ? $displayName : ($tenant->company_name ?? ''),
            'business_num' => $tenant->business_num ?? '',
            'ceo_name' => $tenant->ceo_name ?? '',
            'address' => $tenant->address ?? '',
            'phone' => $tenant->phone ?? '',
        ];
    }

    private function getCardAndAccountData(): array
    {
        $tenantId = session('selected_tenant_id');

        $cards = CorporateCard::forTenant($tenantId)
            ->active()
            ->where('card_name', 'not like', '%하이패스%')
            ->select('id', 'card_name', 'card_company', 'card_number', 'card_holder_name')
            ->get();

        $accounts = BankAccount::where('tenant_id', $tenantId)
            ->active()
            ->ordered()
            ->select('id', 'bank_name', 'account_number', 'account_holder', 'is_primary')
            ->get();

        return [$cards, $accounts];
    }
}
