<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\AdminActivityLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;

class AdminUserController extends Controller
{
    public function index()
    {
        $admins = Admin::withCount([])->latest()->get();
        $activityLog = AdminActivityLog::with('admin')->latest()->take(50)->get();
        return view('admin.admins.index', compact('admins', 'activityLog'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'     => ['required', 'string', 'max:100'],
            'email'    => ['required', 'email', 'unique:admins,email'],
            'role'     => ['required', 'in:admin,super_admin'],
            'password' => ['required', Password::min(8)],
        ]);

        $admin = Admin::create([
            'name'     => $data['name'],
            'email'    => $data['email'],
            'role'     => $data['role'],
            'password' => Hash::make($data['password']),
            'status'   => 'active',
        ]);

        AdminActivityLog::create([
            'admin_id'    => Auth::guard('admin')->id(),
            'action'      => 'admin.create',
            'target_type' => Admin::class,
            'target_id'   => $admin->id,
            'meta'        => ['name' => $admin->name, 'role' => $admin->role],
            'ip_address'  => request()->ip(),
        ]);

        return redirect()->route('admin.admins.index')
            ->with('success', 'Admin account created for ' . $admin->name . '.');
    }

    public function toggleStatus(Admin $admin)
    {
        if ($admin->id === Auth::guard('admin')->id()) {
            return redirect()->route('admin.admins.index')
                ->with('error', 'You cannot deactivate your own account.');
        }

        $newStatus = $admin->status === 'active' ? 'inactive' : 'active';
        $admin->update(['status' => $newStatus]);

        AdminActivityLog::create([
            'admin_id'    => Auth::guard('admin')->id(),
            'action'      => 'admin.' . $newStatus,
            'target_type' => Admin::class,
            'target_id'   => $admin->id,
            'meta'        => ['name' => $admin->name],
            'ip_address'  => request()->ip(),
        ]);

        return redirect()->route('admin.admins.index')
            ->with('success', 'Admin account ' . $newStatus . '.');
    }
}
