<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    /**
     * Show the login form
     */
    public function showLogin()
    {
        // If already authenticated, redirect to upload page
        if (session()->has('authenticated')) {
            return redirect()->route('upload.index');
        }

        return view('auth.login');
    }

    /**
     * Handle login
     */
    public function login(Request $request)
    {
        $request->validate([
            'password' => 'required|string',
        ]);

        $adminPassword = env('ADMIN_PASSWORD', 'admin123');

        // Check if password matches (support both plain text and hashed)
        $passwordMatch = false;
        
        if (Hash::check($request->password, $adminPassword)) {
            // Password is hashed in .env
            $passwordMatch = true;
        } elseif ($request->password === $adminPassword) {
            // Password is plain text in .env (for development)
            $passwordMatch = true;
        }

        if (!$passwordMatch) {
            throw ValidationException::withMessages([
                'password' => ['The provided password is incorrect.'],
            ]);
        }

        // Set authenticated session
        session(['authenticated' => true]);

        return redirect()->intended(route('upload.index'));
    }

    /**
     * Handle logout
     */
    public function logout(Request $request)
    {
        session()->forget('authenticated');
        session()->flush();

        return redirect()->route('login');
    }
}

