<?php

namespace App\Http\Controllers\Admin;

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

use App\Models\TenantCategory;
use App\Services\TenantSyncService;
use Illuminate\Support\Str;

class TenantCategoryController extends Controller
{
    protected $syncService;

    public function __construct(TenantSyncService $syncService)
    {
        $this->syncService = $syncService;
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $categories = TenantCategory::latest()->paginate(10);
        return view('admin.tenant-categories.index', compact('categories'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('admin.tenant-categories.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:tenant_categories',
            'description' => 'nullable|string',
            'is_active' => 'boolean',
            'settings' => 'nullable|array',
            'default_categories' => 'nullable|string',
        ]);

        $validated['slug'] = Str::slug($validated['name']);
        $validated['is_active'] = $request->has('is_active');
        $validated['settings'] = $request->input('settings', []);
        
        // Convert comma separated string to array
        if ($request->filled('default_categories')) {
            $validated['default_categories'] = array_map('trim', explode(',', $request->default_categories));
        } else {
            $validated['default_categories'] = [];
        }

        TenantCategory::create($validated);

        return redirect()->route('admin.tenant-categories.index')->with('success', 'Tenant category created successfully.');
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(TenantCategory $tenantCategory)
    {
        return view('admin.tenant-categories.edit', compact('tenantCategory'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, TenantCategory $tenantCategory)
    { 
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:tenant_categories,name,' . $tenantCategory->id,
            'description' => 'nullable|string',
            'is_active' => 'boolean',
            'settings' => 'nullable|array',
            'default_categories' => 'nullable|string',
        ]);

        $validated['slug'] = Str::slug($validated['name']);
        $validated['is_active'] = $request->has('is_active');
        $validated['settings'] = $request->input('settings', []);
        
        if ($request->filled('default_categories')) {
            $validated['default_categories'] = array_map('trim', explode(',', $request->default_categories));
        } else {
            $validated['default_categories'] = [];
        }

        $tenantCategory->update($validated);

        // Sync to all associated tenants
        $this->syncService->syncTenantCategoryToAll($tenantCategory);

        return redirect()->route('admin.tenant-categories.index')->with('success', 'Tenant category updated and synced to all tenants.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(TenantCategory $tenantCategory)
    {
        if ($tenantCategory->tenants()->count() > 0) {
            return back()->with('error', 'Cannot delete category with associated tenants.');
        }

        $tenantCategory->delete();

        return redirect()->route('admin.tenant-categories.index')->with('success', 'Tenant category deleted successfully.');
    }
}
