<?php

namespace App\Http\Controllers\Sales;

use App\Http\Controllers\Controller;
use App\Services\Sales\BusinessCardRequestService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;

class BusinessCardRequestController extends Controller
{
    public function __construct(
        private BusinessCardRequestService $service
    ) {}

    /**
     * 파트너 명함신청 (신청폼 + 이력) - 모든 사용자
     */
    public function index(Request $request): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('sales.business-cards.index'));
        }

        $user = auth()->user();
        $myRequests = $this->service->getMyRequests($user->id);

        return view('sales.business-cards.partner-index', compact('user', 'myRequests'));
    }

    /**
     * 명함신청 처리 (관리자 전용)
     */
    public function manage(Request $request): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('sales.business-cards.manage'));
        }

        if (! auth()->user()->isAdmin()) {
            abort(403, '관리자만 접근할 수 있습니다.');
        }

        $search = $request->get('search');
        $stats = $this->service->getStats();
        $pendingRequests = $this->service->getPendingRequests($search);
        $orderedRequests = $this->service->getOrderedRequests($search);
        $processedRequests = $this->service->getProcessedRequests($search);

        return view('sales.business-cards.admin-index', compact(
            'stats',
            'pendingRequests',
            'orderedRequests',
            'processedRequests',
            'search'
        ));
    }

    /**
     * 명함 신청 등록
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:50',
            'phone' => 'required|string|max:20',
            'title' => 'nullable|string|max:50',
            'email' => 'nullable|email|max:100',
            'quantity' => 'nullable|integer|min:1|max:9999',
            'memo' => 'nullable|string|max:1000',
        ]);

        $this->service->createRequest($validated);

        return redirect()->route('sales.business-cards.index')
            ->with('success', '명함 신청이 완료되었습니다.');
    }

    /**
     * 제작의뢰 (관리자 전용)
     */
    public function order(Request $request, int $id)
    {
        if (! auth()->user()->isAdmin()) {
            abort(403, '관리자만 처리할 수 있습니다.');
        }

        $this->service->order($id);

        if ($request->expectsJson() || $request->header('Accept') === 'application/json') {
            return response()->json([
                'success' => true,
                'message' => '제작의뢰 처리되었습니다.',
            ]);
        }

        return redirect()->route('sales.business-cards.manage')
            ->with('success', '제작의뢰 처리되었습니다.');
    }

    /**
     * 처리 완료 (관리자 전용)
     */
    public function process(Request $request, int $id)
    {
        if (! auth()->user()->isAdmin()) {
            abort(403, '관리자만 처리할 수 있습니다.');
        }

        $validated = $request->validate([
            'process_memo' => 'nullable|string|max:1000',
        ]);

        $this->service->process($id, $validated['process_memo'] ?? null);

        if ($request->expectsJson() || $request->header('Accept') === 'application/json') {
            return response()->json([
                'success' => true,
                'message' => '처리가 완료되었습니다.',
            ]);
        }

        return redirect()->route('sales.business-cards.manage')
            ->with('success', '처리가 완료되었습니다.');
    }

    /**
     * 처리완료 건 삭제 (관리자 전용)
     */
    public function destroy(Request $request, int $id)
    {
        if (! auth()->user()->isAdmin()) {
            abort(403, '관리자만 삭제할 수 있습니다.');
        }

        $this->service->delete($id);

        if ($request->expectsJson() || $request->header('Accept') === 'application/json') {
            return response()->json([
                'success' => true,
                'message' => '삭제되었습니다.',
            ]);
        }

        return redirect()->route('sales.business-cards.manage')
            ->with('success', '삭제되었습니다.');
    }
}
