<?php

namespace App\Http\Controllers\Modules\MasterData;

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

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

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

    /**
     * Alias for index() - backward compatibility with old routes
     */
    public function companyTypes()
    {
        return $this->index();
    }

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

    /**
     * Store a newly created company type
     */
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'company_type' => 'required|string|max:255|unique:company_types,companytype,NULL,id,deleted_at,NULL',
        ]);

        CompanyType::create([
            'companytype' => $validated['company_type'],
        ]);

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

    /**
     * Update the specified company type
     */
    public function update(Request $request, CompanyType $companytype): JsonResponse
    {
        $validated = $request->validate([
            'company_type' => 'required|string|max:255|unique:company_types,companytype,NULL,id,deleted_at,NULL' . $companytype->id,
        ]);

        $companytype->update([
            'companytype' => $validated['company_type'],
        ]);

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

    /**
     * Remove the specified company type
     */
    public function destroy(CompanyType $companytype): JsonResponse
    {
        $companytype->delete();

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

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