<?php

namespace App\Http\Controllers\Agency\Customer;

use App\Http\Controllers\Controller;
use App\Models\Customer\CustomerDocumentType;
use Illuminate\Http\Request;

class CustomerDocumentTypeController extends Controller
{
    public function index()
    {
        $agencyId = auth()->user()->agency_id;
        $types = CustomerDocumentType::byAgency($agencyId)->orderBy('sort_order')->get();
        return view('agency.settings.customers.document-types.index', compact('types'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string|max:500',
            'is_required' => 'boolean',
            'sort_order' => 'integer',
        ]);

        CustomerDocumentType::create([
            'agency_id' => auth()->user()->agency_id,
            'name' => $request->name,
            'description' => $request->description,
            'is_required' => $request->has('is_required'),
            'sort_order' => $request->sort_order ?? 0,
            'is_active' => true,
        ]);

        return redirect()->back()->with('success', 'Döküman tipi başarıyla oluşturuldu.');
    }

    public function update(Request $request, CustomerDocumentType $type)
    {
        $this->authorizeAgency($type->agency_id);

        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string|max:500',
            'is_required' => 'boolean',
            'sort_order' => 'integer',
            'is_active' => 'boolean',
        ]);

        $type->update($request->all());

        return redirect()->back()->with('success', 'Döküman tipi güncellendi.');
    }

    public function destroy(CustomerDocumentType $type)
    {
        $this->authorizeAgency($type->agency_id);
        $type->delete();
        return redirect()->back()->with('success', 'Döküman tipi silindi.');
    }

    private function authorizeAgency($agencyId)
    {
        if ($agencyId !== auth()->user()->agency_id) {
            abort(403);
        }
    }
}
