<?php

namespace App\Http\Controllers\Auth;

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

class AuthenticatedSessionController extends Controller
{
    /**
     * Show login page
     */
    public function create()
    {
        return view('app.auth.login');
    }

    /**
     * Handle login
     */
    public function store(Request $request)
    {
        $phone = $request->input('phone');
        $password = $request->input('password');

        // Check if fields are empty
        if (!$phone) {
            return $this->ajaxOrRedirect($request, false, 'Phone field is required.');
        }
        if (!$password) {
            return $this->ajaxOrRedirect($request, false, 'Password field is required.');
        }

        $user = User::where('phone', $phone)->first();

        if (!$user) {
            return $this->ajaxOrRedirect($request, false, 'This phone number is not registered.');
        }

        if (!Hash::check($password, $user->password)) {
            return $this->ajaxOrRedirect($request, false, 'Incorrect password.');
        }

        // Login success
        Auth::login($user);

        return $this->ajaxOrRedirect($request, true, 'Login successful.', route('dashboard'));
    }

    /**
     * Logout
     */
    public function destroy(Request $request): RedirectResponse
    {
        session()->put('visibility', false);
        Auth::guard('web')->logout();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/login');
    }

    /**
     * Return JSON for AJAX or redirect for normal request
     */
    protected function ajaxOrRedirect(Request $request, bool $success, string $message, string $redirect = null)
    {
        if ($request->ajax()) {
            return response()->json([
                'success' => $success,
                'message' => $message,
                'redirect' => $redirect
            ]);
        }

        if ($success) {
            return redirect()->route('dashboard')->with('success', $message);
        }

        return redirect()->route('login')->with('error', $message);
    }
}
