<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\CompanyType;
use Illuminate\Http\Request;

use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;

class SuperAdminCompanyTypeController extends Controller
{
    public function companyTypes()
    {
        return view('superadmin.master.companytype');
    }

    public function list()
    {
        $companytypes = CompanyType::select('id', 'companytype')->get();
        return response()->json(['data' => $companytypes]);
    }

    public function store_old(Request $request)
    {
        $validated = $request->validate([
            'company_type' => 'required|string|max:255',
        ]);

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

        return response()->json(['success' => true, 'message' => 'Company Type Added']);
    }
    
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'company_type' => 'required|unique:company_types,companytype|max:255',
        ]);
    
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }
    
        CompanyType::create(['companytype' => $request->company_type]);
    
        return response()->json(['success' => true, 'message' => 'Company Type added']);
    }

    public function update_old(Request $request, CompanyType $companytype)
    {
        $validated = $request->validate([
            'company_type' => 'required|string|max:255',
        ]);

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

        return response()->json(['success' => true, 'message' => 'Company Type Updated']);
    }
    
    public function update(Request $request, CompanyType $companytype)
    {
        $validator = Validator::make($request->all(), [
            'company_type' => [
                'required',
                'max:255',
                Rule::unique('company_types', 'companytype')->ignore($companytype->id),
            ],
        ]);
    
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }
    
        $companytype->update(['companytype' => $request->company_type]);
    
        return response()->json(['success' => true, 'message' => 'Company Type updated']);
    }

    public function delete(CompanyType $companytype)
    {
        $companytype->delete();
        return response()->json(['success' => true, 'message' => 'Company Type Deleted']);
    }
}
