<?php

namespace App\Http\Controllers\Modules\MasterData;

use App\Http\Controllers\Controller;
use App\Http\Traits\HasRoleViews;
use App\Models\AccountType;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

/**
 * Unified AccountType Controller
 *
 * Handles account type management for all roles (Admin, Manager, SuperAdmin).
 * Views are automatically resolved based on the logged-in user's role.
 */
class AccountTypeController extends Controller
{
    use HasRoleViews;

    /**
     * Display the account types management page
     */
    public function index()
    {
        return $this->roleView('master.accounttype');
    }

    /**
     * Get account types list for DataTable/AJAX
     */
    public function list(): JsonResponse
    {
        $types = AccountType::select('id', 'accounttype')->get();
        return response()->json(['data' => $types]);
    }

    /**
     * Get a single account type for editing
     */
    public function show(AccountType $accounttype): JsonResponse
    {
        return response()->json($accounttype);
    }

    /**
     * Store a newly created account type
     */
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'account_type' => 'required|string|max:255|unique:account_types,accounttype',
        ]);

        AccountType::create([
            'accounttype' => $validated['account_type'],
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Account Type added successfully',
        ]);
    }

    /**
     * Update the specified account type
     */
    public function update(Request $request, AccountType $accounttype): JsonResponse
    {
        $validated = $request->validate([
            'account_type' => 'required|string|max:255|unique:account_types,accounttype,' . $accounttype->id,
        ]);

        $accounttype->update([
            'accounttype' => $validated['account_type'],
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Account Type updated successfully',
        ]);
    }

    /**
     * Remove the specified account type
     */
    public function destroy(AccountType $accounttype): JsonResponse
    {
        $accounttype->delete();

        return response()->json([
            'success' => true,
            'message' => 'Account Type deleted successfully',
        ]);
    }

    /**
     * Alias for destroy() - backward compatibility with old routes
     */
    public function delete(AccountType $accounttype): JsonResponse
    {
        return $this->destroy($accounttype);
    }
}
