<?php

namespace App\Http\Controllers\Sales;

use App\Http\Controllers\Controller;
use App\Models\Sales\SalesManager;
use App\Models\Sales\SalesProspect;
use App\Models\Sales\SalesRecord;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;

/**
 * 영업 실적 관리 컨트롤러
 */
class SalesRecordController extends Controller
{
    /**
     * 목록 페이지
     */
    public function index(Request $request): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('sales.records.index'));
        }

        $query = SalesRecord::with(['manager', 'prospect']);

        // 검색
        if ($search = $request->get('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('description', 'like', "%{$search}%")
                    ->orWhere('record_type', 'like', "%{$search}%")
                    ->orWhereHas('prospect', function ($q2) use ($search) {
                        $q2->where('company_name', 'like', "%{$search}%");
                    });
            });
        }

        // 상태 필터
        if ($status = $request->get('status')) {
            $query->where('status', $status);
        }

        // 담당자 필터
        if ($managerId = $request->get('manager_id')) {
            $query->where('manager_id', $managerId);
        }

        // 기간 필터
        if ($startDate = $request->get('start_date')) {
            $query->where('record_date', '>=', $startDate);
        }
        if ($endDate = $request->get('end_date')) {
            $query->where('record_date', '<=', $endDate);
        }

        $records = $query->orderByDesc('record_date')->paginate(20);

        // 통계
        $stats = [
            'total_count' => SalesRecord::count(),
            'pending_count' => SalesRecord::pending()->count(),
            'approved_count' => SalesRecord::approved()->count(),
            'total_amount' => SalesRecord::sum('amount'),
            'total_commission' => SalesRecord::sum('commission'),
            'pending_amount' => SalesRecord::pending()->sum('amount'),
            'approved_amount' => SalesRecord::approved()->sum('amount'),
        ];

        $managers = SalesManager::active()->orderBy('name')->get();

        return view('sales.records.index', compact('records', 'stats', 'managers'));
    }

    /**
     * 등록 폼
     */
    public function create(): View
    {
        $managers = SalesManager::active()->orderBy('name')->get();
        $prospects = SalesProspect::orderBy('company_name')->get();

        return view('sales.records.create', compact('managers', 'prospects'));
    }

    /**
     * 등록 처리
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'manager_id' => 'required|exists:sales_managers,id',
            'prospect_id' => 'nullable|exists:sales_prospects,id',
            'record_date' => 'required|date',
            'record_type' => 'required|string|max:50',
            'amount' => 'required|numeric|min:0',
            'commission' => 'nullable|numeric|min:0',
            'description' => 'nullable|string',
            'status' => 'required|in:pending,approved,rejected,paid',
        ]);

        SalesRecord::create($validated);

        return redirect()->route('sales.records.index')
            ->with('success', '실적이 등록되었습니다.');
    }

    /**
     * 상세 페이지
     */
    public function show(int $id): View
    {
        $record = SalesRecord::with(['manager', 'prospect'])->findOrFail($id);

        return view('sales.records.show', compact('record'));
    }

    /**
     * 수정 폼
     */
    public function edit(int $id): View
    {
        $record = SalesRecord::findOrFail($id);
        $managers = SalesManager::active()->orderBy('name')->get();
        $prospects = SalesProspect::orderBy('company_name')->get();

        return view('sales.records.edit', compact('record', 'managers', 'prospects'));
    }

    /**
     * 수정 처리
     */
    public function update(Request $request, int $id)
    {
        $record = SalesRecord::findOrFail($id);

        $validated = $request->validate([
            'manager_id' => 'required|exists:sales_managers,id',
            'prospect_id' => 'nullable|exists:sales_prospects,id',
            'record_date' => 'required|date',
            'record_type' => 'required|string|max:50',
            'amount' => 'required|numeric|min:0',
            'commission' => 'nullable|numeric|min:0',
            'description' => 'nullable|string',
            'status' => 'required|in:pending,approved,rejected,paid',
        ]);

        $record->update($validated);

        return redirect()->route('sales.records.index')
            ->with('success', '실적이 수정되었습니다.');
    }

    /**
     * 삭제 처리
     */
    public function destroy(int $id)
    {
        $record = SalesRecord::findOrFail($id);
        $record->delete();

        return redirect()->route('sales.records.index')
            ->with('success', '실적이 삭제되었습니다.');
    }
}
