<?php

namespace App\Http\Controllers\SoftwareLicense;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\SoftwareLicense\SoftwareLicenseCategoryRequest;
use App\Models\SoftwareLicense\SoftwareLicenseCategory;
use App\Models\AssetHistory;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

/**
 * Software License Category Controller
 */
class SoftwareLicenseCategoryController extends Controller
{

    /**
     * Initialize the controller with the SoftwareLicenseCategory and AssetHistory models.
     *
     * @param \App\Models\SoftwareLicenseCategory $categoryModel     The model to manage software license categories
     * @param \App\Models\AssetHistory            $assetHistoryModel The model to manage asset history
     */
    public function __construct(protected SoftwareLicenseCategory $categoryModel, protected AssetHistory $assetHistoryModel)
    {
    }

    /**
     * Display the index view for software license categories.
     *
     * @return \Illuminate\View\View The view for the software license categories index
     */
    public function index()
    {
        $categories = $this->categoryModel->orderBy('name')->get();

        return view('software-license.category.index', compact('categories'));
    }

    /**
     * Store a new software license category.
     *
     * @return \Illuminate\Http\RedirectResponse The redirect response to the software assets categories page with a success or error message
     */
    public function store()
    {
        request()->validate(
            [
                'name' => 'required|unique:software_license_categories,name',
            ],
            [
                'name.required' => 'The category name is required',
                'name.unique' => 'Category already exists',
            ]
        );

        $name = request('name');
        $categoryData = $this->categoryModel->where('name', $name)->first();

        if (!$categoryData) {
            $this->categoryModel->create(['name' => $name]);

            $description = __('license-history.SoftwareLicenseCategoryCreated', [
                'category' => $name
            ]);

            $assetHistory = [
                'user_id' => Auth::id(),
                'action' => 'software_license_category_created',
                'description' => $description,
                'created_at'  => Carbon::now()->format('Y-m-d H:i:s'),
                'updated_at'  => Carbon::now()->format('Y-m-d H:i:s'),
            ];

            $this->assetHistoryModel->create($assetHistory);

            return redirect('/software-assets-categories');
        } else {
            return redirect('/software-assets-categories')->withErrors(['Category already exists']);
        }
    }

    /**
     * Handle AJAX requests for software license categories.
     *
     * @param \App\Http\Requests\SoftwareLicenseCategoryRequest $request The incoming request instance
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse The JSON response indicating success or a redirect response from the called method
     */
    public function ajax(SoftwareLicenseCategoryRequest $request)
    {
        if (request('action') == 'edit') {
            return $this->update($request);
        } elseif (request('action') == 'delete') {
            return $this->destroy();
        }

        return response()->json(true);
    }

    /**
     * Update a software license category.
     *
     * @param \App\Http\Requests\SoftwareLicenseCategoryRequest $request The incoming request instance
     *
     * @return \Illuminate\Http\JsonResponse The JSON response indicating the success of the update operation
     */
    public function update(SoftwareLicenseCategoryRequest $request)
    {
        $category = $this->categoryModel->findOrFail(request('category_id'));
        $oldName = $category->name;
        $category->update(['name' => request('name')]);
        $description = '';

        if ($oldName != request('name')) {
            $description .= __('history.FieldsUpdated', [
                'fieldName' => 'Name',
                'oldValue'  => $oldName,
                'newValue'  => $request->name,
            ]);
        }

        $description = __('license-history.SoftwareLicenseCategoryUpdated', [
            'description' => $description
        ]);

        $assetHistory = [
            'user_id' => Auth::id(),
            'action' => 'software_license_category_updated',
            'description' => $description,
            'created_at'  => Carbon::now()->format('Y-m-d H:i:s'),
            'updated_at'  => Carbon::now()->format('Y-m-d H:i:s'),
        ];

        $this->assetHistoryModel->create($assetHistory);

        return response()->json(['status' => 'success', 'message' => 'Category updated successfully']);
    }

    /**
     * Delete a software license category.
     *
     * @return \Illuminate\Http\JsonResponse The JSON response indicating the success or failure of the delete operation
     */
    public function destroy()
    {
        $category = $this->categoryModel->findOrFail(request('category_id'));

        if (count($category->licenses)) {
            return response()->json(['status' => 'error', 'message' => 'This Category cannot be deleted as it has licenses associated with it']);
        }

        $name = $category->name;
        $category->delete();

        $description = __('license-history.SoftwareLicenseCategoryDeleted', [
            'category' => $name
        ]);

        $assetHistory = [
            'user_id' => Auth::id(),
            'action' => 'software_license_category_deleted',
            'description' => $description,
            'created_at'  => Carbon::now()->format('Y-m-d H:i:s'),
            'updated_at'  => Carbon::now()->format('Y-m-d H:i:s'),
        ];

        $this->assetHistoryModel->create($assetHistory);

        return response()->json(['status' => 'success', 'message' => 'Category deleted successfully']);
    }

    /**
     * Search for software license categories.
     *
     * @return \Illuminate\Http\JsonResponse The JSON response containing the rendered view of the search results
     */
    public function search()
    {
        $name = request('searchText');
        $categories = $this->categoryModel;

        if ($name) {
            $categories = $categories->where('name', 'like',  '%' . $name . '%');
        }

        $categories = $categories->get();

        $view['categories'] = view('software-license.category.list', compact('categories'))->render();

        return response()->json($view);
    }
}
