<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\PartyType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\Rule;

class PartyTypesController extends Controller
{
    /**
     * Resolve index route name (supports both with/without "party." prefix).
     */
    protected function indexRouteName(): ?string
    {
        foreach (['party.party_types.index', 'party_types.index'] as $name) {
            if (Route::has($name)) return $name;
        }
        return null;
    }

    /**
     * Redirect helper that safely targets the right index route.
     */
    protected function redirectToIndex(string $msg)
    {
        if ($route = $this->indexRouteName()) {
            return redirect()->route($route)->with('success', $msg);
        }
        return redirect('/party-types')->with('success', $msg);
    }

    /**
     * List party types with simple search + pagination.
     */
    public function index(Request $request)
    {
        $q  = trim((string) $request->get('q'));
        $pk = (new PartyType)->getKeyName();

        $partyTypes = PartyType::query()
            ->with(['creator:id,name', 'updater:id,name']) // show real user names
            ->when($q, fn ($w) => $w->where('name', 'like', "%{$q}%"))
            ->orderBy($pk, 'desc')
            ->paginate(12)
            ->withQueryString();

        return view('party.party_types.index', compact('partyTypes', 'q'));
    }

    /**
     * Show create form.
     */
    public function create()
    {
        return view('party.party_types.create');
    }

    /**
     * Store a new party type.
     */
    public function store(Request $request)
    {
        $table = (new PartyType)->getTable();   // e.g. rm_party_types

        $data = $request->validate([
            'name'   => ['required', 'string', 'max:255', Rule::unique($table, 'name')],
            'status' => ['nullable', 'in:0,1'],
        ]);

        $data['status'] = (int)($data['status'] ?? 1);

        DB::transaction(function () use (&$data, $table) {
            if (Schema::hasColumn($table, 'created_by')) $data['created_by'] = Auth::id();
            if (Schema::hasColumn($table, 'updated_by')) $data['updated_by'] = Auth::id();
            PartyType::create($data);
        });

        return $this->redirectToIndex('Party type created successfully.');
    }

    /**
     * (Optional) Show a single party type.
     */
    public function show(PartyType $partyType)
    {
        return view('party.party_types.show', compact('partyType'));
    }

    /**
     * Show edit form.
     */
    public function edit(PartyType $partyType)
    {
        return view('party.party_types.edit', compact('partyType'));
    }

    /**
     * Update an existing party type.
     */
    public function update(Request $request, PartyType $partyType)
    {
        $table = (new PartyType)->getTable();
        $pk    = $partyType->getKeyName();

        $data = $request->validate([
            'name'   => [
                'required', 'string', 'max:255',
                Rule::unique($table, 'name')->ignore($partyType->getKey(), $pk),
            ],
            'status' => ['nullable', 'in:0,1'],
        ]);

        $data['status'] = (int)($data['status'] ?? $partyType->status);

        DB::transaction(function () use (&$data, $partyType, $table) {
            if (Schema::hasColumn($table, 'updated_by')) $data['updated_by'] = Auth::id();
            $partyType->update($data);
        });

        return $this->redirectToIndex('Party type updated successfully.');
    }

    /**
     * Delete a party type.
     */
    public function destroy(PartyType $partyType)
    {
        $partyType->delete();
        return $this->redirectToIndex('Party type deleted successfully.');
    }
}
