<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class SystemController extends Controller
{
   
    public function index()
    {
        if (!Auth::check() || Auth::user()->role !== 'admin') {
            abort(403, 'Akses ditolak. Hanya admin yang dapat membuka halaman ini.');
        }

        $users = User::orderBy('name')->get();
        return view('admin.system', compact('users'));
    }

    public function makeAdmin(Request $request)
    {
        if (!Auth::check() || Auth::user()->role !== 'admin') {
            abort(403, 'Akses ditolak.');
        }

        $request->validate(['user_id' => 'required|exists:users,id']);
        $user = User::findOrFail($request->user_id);

        $user->role = 'admin';
        $user->save();

        return back()->with('success', "{$user->name} sekarang menjadi admin.");
    }

    
    public function removeAdmin(Request $request)
    {
        if (!Auth::check() || Auth::user()->role !== 'admin') {
            abort(403, 'Akses ditolak.');
        }

        $request->validate(['user_id' => 'required|exists:users,id']);
        $user = User::findOrFail($request->user_id);

        if ($user->id === Auth::id()) {
            return back()->with('error', 'Anda tidak dapat mencabut status admin Anda sendiri.');
        }

        $user->role = 'user';
        $user->save();

        return back()->with('success', "Status admin untuk {$user->name} telah dicabut.");
    }

    public function block(Request $request)
    {
        if (!Auth::check() || Auth::user()->role !== 'admin') {
            abort(403, 'Akses ditolak.');
        }

        $request->validate(['user_id' => 'required|exists:users,id']);

        $user = User::find($request->user_id);

        if (!$user) {
            return back()->with('error', 'User tidak ditemukan.');
        }

        if ($user->role === 'admin') {
            return back()->with('error', 'Tidak dapat memblokir admin.');
        }

        $user->blocked_at = now();
        $user->save();

        return back()->with('success', "User {$user->name} telah diblokir.");
    }

   
    public function unblock(Request $request)
    {
        if (!Auth::check() || Auth::user()->role !== 'admin') {
            abort(403, 'Akses ditolak.');
        }

        $request->validate(['user_id' => 'required|exists:users,id']);

        $user = User::find($request->user_id);

        if (!$user) {
            return back()->with('error', 'User tidak ditemukan.');
        }

        $user->blocked_at = null;
        $user->save();

        return back()->with('success', "Blokir untuk {$user->name} telah dibuka.");
    }
}
