<?php

namespace App\Http\Controllers\Admin;

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

class AuthController extends Controller
{
    public function showLogin()
    {
        if (session('admin_id')) {
            return redirect()->route('admin.dashboard');
        }

        return view('admin.auth.login');
    }

    public function login(Request $request)
    {
        $data = $request->validate([
            'phone' => 'required|string',
        ]);

        $user = User::findByPhone($data['phone']);

        if (! $user || $user->role !== 'admin') {
            return back()->with('error', 'رقم الهاتف غير مسجّل كمدير نظام');
        }

        if (! $user->is_active) {
            return back()->with('error', 'حسابك موقوف');
        }

        session(['admin_id' => $user->id]);

        return redirect()->route('admin.dashboard');
    }

    public function logout()
    {
        session()->forget('admin_id');

        return redirect()->route('login')
            ->with('success', 'تم تسجيل الخروج بنجاح');
    }
}
