<?php

namespace App\Http\Controllers;

use App\Models\AccessCatalog;
use App\Models\Department;
use App\Models\SystemLog;
use Illuminate\Http\Request;

class AccessCatalogController extends Controller
{
    public function index(Request $request)
    {
        $query = AccessCatalog::with('ownerDepartment');

        // Filter by category
        if ($request->filled('category')) {
            $query->where('category', $request->category);
        }

        $accessCatalogs = $query->latest()->paginate(20);

        // Get total counts per category for stats (independent of filter)
        $categoryCounts = AccessCatalog::groupBy('category')
            ->selectRaw('category, count(*) as count')
            ->pluck('count', 'category');

        $selectedCategory = $request->get('category');

        return view('access-catalogs.index', compact('accessCatalogs', 'categoryCounts', 'selectedCategory'));
    }

    public function create()
    {
        $departments = Department::all();
        $categories = [
            'physical' => 'Akses Fisik',
            'digital' => 'Akses Digital',
            'network' => 'Akses Network',
            'application' => 'Aplikasi',
            'cloud' => 'Cloud Service',
            'file' => 'File Storage',
            'other' => 'Lainnya'
        ];

        return view('access-catalogs.create', compact('departments', 'categories'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'code' => 'required|unique:access_catalogs|max:30',
            'name' => 'required|string|max:100',
            'category' => 'required|in:physical,digital,network,application,cloud,file,other',
            'description' => 'nullable|string',
            'criticality_level' => 'required|in:low,medium,high,critical',
            'owner_department_id' => 'nullable|exists:departments,id',
            'revocation_procedure' => 'nullable|string',
        ]);

        $validated['created_by'] = auth()->id();
        $validated['is_active'] = true;

        $catalog = AccessCatalog::create($validated);

        SystemLog::logCreate(
            auth()->id(),
            'access_catalog',
            $catalog->id,
            $catalog->toArray()
        );

        return redirect()->route('access-catalogs.index')
            ->with('success', 'Katalog akses berhasil ditambahkan.');
    }

    public function edit(AccessCatalog $accessCatalog)
    {
        $departments = Department::all();
        $categories = [
            'physical' => 'Akses Fisik',
            'digital' => 'Akses Digital',
            'network' => 'Akses Network',
            'application' => 'Aplikasi',
            'cloud' => 'Cloud Service',
            'file' => 'File Storage',
            'other' => 'Lainnya'
        ];

        return view('access-catalogs.edit', compact('accessCatalog', 'departments', 'categories'));
    }

    public function update(Request $request, AccessCatalog $accessCatalog)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'category' => 'required|in:physical,digital,network,application,cloud,file,other',
            'description' => 'nullable|string',
            'criticality_level' => 'required|in:low,medium,high,critical',
            'owner_department_id' => 'nullable|exists:departments,id',
            'revocation_procedure' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        $oldValues = $accessCatalog->toArray();
        $accessCatalog->update($validated);

        SystemLog::logUpdate(
            auth()->id(),
            'access_catalog',
            $accessCatalog->id,
            $oldValues,
            $accessCatalog->fresh()->toArray()
        );

        return redirect()->route('access-catalogs.index')
            ->with('success', 'Katalog akses berhasil diupdate.');
    }

    public function destroy(AccessCatalog $accessCatalog)
    {
        // Cek apakah sudah dipakai
        if ($accessCatalog->employeeAccessDetails()->count() > 0) {
            return back()->with('error', 'Katalog akses tidak bisa dihapus karena sudah digunakan.');
        }

        $oldValues = $accessCatalog->toArray();
        $accessCatalog->delete();

        SystemLog::logDelete(
            auth()->id(),
            'access_catalog',
            $accessCatalog->id,
            $oldValues
        );

        return redirect()->route('access-catalogs.index')
            ->with('success', 'Katalog akses berhasil dihapus.');
    }

    // API: Get all catalogs for dropdown
    public function getCatalogsApi()
    {
        $catalogs = AccessCatalog::active()
            ->get(['id', 'code', 'name', 'category', 'criticality_level']);

        return $this->successResponse($catalogs);
    }
}