<?php

namespace App\Http\Controllers\Company\FixedAssets;

use App\Models\{AuditLog, FixedAssetCategory};
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class FixedAssetCategoriesController extends FixedAssetsBaseController
{
    public function index(Request $request)
    {
        $this->ensureFixedAssetsModule();
        $this->gate('view');

        $cid = $this->companyId();
        $query = FixedAssetCategory::withoutGlobalScopes()->where('company_id', $cid);

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where('name', 'like', "%{$search}%");
        }
        if ($request->filled('status')) {
            $query->where('is_active', $request->status === 'active');
        }

        $records = $query->orderBy('name')->paginate(25)->withQueryString();
        $stats = [
            'total'  => FixedAssetCategory::withoutGlobalScopes()->where('company_id', $cid)->count(),
            'active' => FixedAssetCategory::withoutGlobalScopes()->where('company_id', $cid)->where('is_active', true)->count(),
        ];

        return view('fixed-assets.categories.index', compact('records', 'stats'));
    }

    public function store(Request $request)
    {
        $this->ensureFixedAssetsModule();
        $this->gate('edit');

        $cid = $this->companyId();
        $validated = $request->validate([
            'name' => [
                'required', 'string', 'max:120',
                Rule::unique('fixed_asset_categories')->where(fn ($q) => $q->where('company_id', $cid)),
            ],
        ]);

        $record = FixedAssetCategory::withoutGlobalScopes()->create(array_merge($validated, [
            'company_id' => $cid,
            'is_active'  => true,
        ]));

        AuditLog::record('create', 'fixed_asset_categories', (string) $record->id, null, ['name' => $record->name], "Asset category created: {$record->name}");

        return back()->with('success', "Category '{$record->name}' created.");
    }

    public function update(Request $request, FixedAssetCategory $fixedAssetCategory)
    {
        $this->ensureFixedAssetsModule();
        $this->gate('edit');
        $this->sameCompany($fixedAssetCategory);

        $cid = $this->companyId();
        $validated = $request->validate([
            'name' => [
                'required', 'string', 'max:120',
                Rule::unique('fixed_asset_categories')->where(fn ($q) => $q->where('company_id', $cid))->ignore($fixedAssetCategory->id),
            ],
            'is_active' => 'boolean',
        ]);

        $validated['is_active'] = $request->boolean('is_active');
        $fixedAssetCategory->update($validated);

        AuditLog::record('update', 'fixed_asset_categories', (string) $fixedAssetCategory->id, null, $validated, "Asset category updated: {$fixedAssetCategory->name}");

        return back()->with('success', "Category '{$fixedAssetCategory->name}' updated.");
    }

    public function toggle(FixedAssetCategory $fixedAssetCategory)
    {
        $this->ensureFixedAssetsModule();
        $this->gate('edit');
        $this->sameCompany($fixedAssetCategory);

        $fixedAssetCategory->update(['is_active' => !$fixedAssetCategory->is_active]);

        return back()->with('success', 'Category marked as ' . ($fixedAssetCategory->is_active ? 'active' : 'inactive') . '.');
    }

    public function destroy(FixedAssetCategory $fixedAssetCategory)
    {
        $this->ensureFixedAssetsModule();
        $this->gate('edit');
        $this->sameCompany($fixedAssetCategory);

        if ($fixedAssetCategory->assets()->exists()) {
            return back()->withErrors(['delete' => 'Cannot delete a category that is assigned to assets.']);
        }

        $name = $fixedAssetCategory->name;
        $id = $fixedAssetCategory->id;
        $fixedAssetCategory->delete();

        AuditLog::record('delete', 'fixed_asset_categories', (string) $id, null, null, "Asset category deleted: {$name}");

        return back()->with('success', "Category '{$name}' deleted.");
    }

    private function sameCompany(FixedAssetCategory $category): void
    {
        if ($category->company_id !== $this->companyId()) {
            abort(403);
        }
    }
}
