<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class StaffController extends Controller
{
    public function index()
    {
        $admins = Admin::orderByRaw("FIELD(role, 'super_admin','admin','staff')")->orderByDesc('id')->paginate(15);

        return view('admin.staff.index', compact('admins'));
    }

    public function create()
    {
        $roles = [
            'super_admin' => 'Super Admin',
            'admin' => 'Admin',
            'staff' => 'Staff',
            'demo_admin' => 'Demo Admin (read-only)',
        ];

        $permissions = $this->permissionOptions();

        return view('admin.staff.create', compact('roles', 'permissions'));
    }

    public function store(Request $request)
    {
        $roles = ['super_admin', 'admin', 'staff', 'demo_admin'];

        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', 'unique:admins,email'],
            'role' => ['required', Rule::in($roles)],
            'is_active' => ['nullable', 'boolean'],
            'permissions' => ['nullable', 'array'],
            'permissions.*' => ['string'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);

        $data['is_active'] = $request->boolean('is_active', true);
        $data['permissions'] = $request->input('permissions', []);

        Admin::create($data);

        return redirect()->route('admin.staff.index')->with('success', 'Admin user created successfully.');
    }

    public function edit(Admin $staff)
    {
        $roles = [
            'super_admin' => 'Super Admin',
            'admin' => 'Admin',
            'staff' => 'Staff',
            'demo_admin' => 'Demo Admin (read-only)',
        ];

        return view('admin.staff.edit', [
            'staff' => $staff,
            'roles' => $roles,
            'permissions' => $this->permissionOptions(),
        ]);
    }

    public function update(Request $request, Admin $staff)
    {
        $roles = ['super_admin', 'admin', 'staff', 'demo_admin'];

        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', Rule::unique('admins', 'email')->ignore($staff->id)],
            'role' => ['required', Rule::in($roles)],
            'is_active' => ['nullable', 'boolean'],
            'permissions' => ['nullable', 'array'],
            'permissions.*' => ['string'],
            'password' => ['nullable', 'string', 'min:8', 'confirmed'],
        ]);

        $data['is_active'] = $request->boolean('is_active', true);
        $data['permissions'] = $request->input('permissions', []);

        if (empty($data['password'])) {
            unset($data['password']);
        }

        $staff->update($data);

        return redirect()->route('admin.staff.index')->with('success', 'Admin user updated successfully.');
    }

    public function destroy(Admin $staff)
    {
        if ($staff->isSuperAdmin()) {
            return redirect()->route('admin.staff.index')->withErrors([
                'error' => 'Super Admin accounts cannot be deleted.',
            ]);
        }

        $staff->delete();

        return redirect()->route('admin.staff.index')->with('success', 'Admin user deleted successfully.');
    }

    public function toggleStatus(Admin $staff)
    {
        if ($staff->isSuperAdmin() && !$staff->is_active) {
            $staff->update(['is_active' => true]);
        } else {
            $staff->update(['is_active' => !$staff->is_active]);
        }

        return redirect()->route('admin.staff.index')->with('success', 'Admin status updated.');
    }

    protected function permissionOptions(): array
    {
        return [
            'manage_dashboard' => 'Dashboard and analytics',
            'manage_categories' => 'Categories and subcategories',
            'manage_products' => 'Products and inventory',
            'manage_banners' => 'Banners and promotions',
            'manage_coupons' => 'Coupons and discounts',
            'manage_orders' => 'Orders and order status',
            'manage_customers' => 'Customers and profiles',
            'manage_pages' => 'Content pages',
            'manage_delivery_types' => 'Delivery types and shipping',
            'manage_payment_methods' => 'Payment methods',
            'manage_reviews' => 'Homepage reviews and testimonials',
            'manage_notifications' => 'Push notifications',
            'manage_settings' => 'Global settings and configuration',
            'manage_ai_settings' => 'AI assistant settings',
        ];
    }
}
