<?php

namespace App\Controllers;

use App\Models\EventOrganizerModel;

/**
 * Structurally mirrors AuthController exactly, but for the organizer
 * realm: organizer*-prefixed session keys (see OrganizerAuth's doc
 * comment for why), and logout() deliberately does NOT call the global
 * session()->destroy() the way AuthController/AdminAuthController's do.
 * A staff member demoing the portal, or checking it on a shared device
 * during an event, is a realistic same-browser-two-tabs scenario for
 * this realm specifically — a global destroy() would silently log out
 * whatever staff/admin session happened to be open in another tab.
 * Scoping the removal to just this realm's keys costs nothing (they're
 * already fully namespaced) and removes that footgun.
 */
class EventOrganizerAuthController extends BaseController
{
    private const SESSION_KEYS = ['organizerIsLoggedIn', 'organizerId', 'organizerName', 'organizerEmail'];

    public function showLogin()
    {
        if (session('organizerIsLoggedIn')) {
            return redirect()->to('organizer/dashboard');
        }

        return view('organizer/auth/login', ['pageTitle' => 'Organizer Log In']);
    }

    public function attemptLogin()
    {
        $rules = [
            'email'    => 'required|valid_email',
            'password' => 'required',
        ];

        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('validation', $this->validator);
        }

        $email    = $this->request->getPost('email');
        $password = $this->request->getPost('password');

        $organizer = (new EventOrganizerModel())->verifyCredentials($email, $password);

        if ($organizer === null) {
            return redirect()->back()->withInput()->with('error', 'Invalid email or password.');
        }

        $session = session();
        $session->regenerate();
        $session->set([
            'organizerIsLoggedIn' => true,
            'organizerId'         => $organizer->id,
            'organizerName'       => $organizer->full_name,
            'organizerEmail'      => $organizer->email,
        ]);

        $this->logActivity('events', "Organizer {$organizer->full_name} logged in.");

        return redirect()->to('organizer/dashboard')->with('success', 'Welcome back, ' . $organizer->full_name . '.');
    }

    public function logout()
    {
        if (session('organizerIsLoggedIn')) {
            $this->logActivity('events', 'Organizer ' . session('organizerName') . ' logged out.');
        }

        session()->remove(self::SESSION_KEYS);

        return redirect()->to('organizer/login')->with('success', 'You have been logged out.');
    }
}
