<?php

namespace App\Controllers;

use App\Models\UserModel;

class AuthController extends BaseController
{
    public function index()
    {
        // Jika user sudah login, tidak perlu menampilkan form login lagi.
        if (session()->get('isLoggedIn')) {
            return redirect()->to($this->homePath());
        }

        return view('auth/login');
    }

    public function login()
    {
        // Ambil input dari form login.
        $email    = trim((string) $this->request->getPost('email'));
        $password = (string) $this->request->getPost('password');

        // Validasi sederhana agar email dan password tidak kosong.
        if ($email === '' || $password === '') {
            return redirect()
                ->back()
                ->withInput()
                ->with('error', 'Email dan password wajib diisi.');
        }

        $account = $this->findAccount($email, $password);

        if ($account === null) {
            return redirect()
                ->back()
                ->withInput()
                ->with('error', 'Email atau password tidak sesuai.');
        }

        if ((int) $account['is_active'] !== 1) {
            return redirect()
                ->back()
                ->withInput()
                ->with('error', 'Akun belum aktif.');
        }

        session()->remove('userId');

        session()->set([
            'accountType'        => $account['account_type'],
            'accountId'          => $account['account_id'],
            'userName'           => $account['name'],
            'userEmail'          => $account['email'],
            'userRole'           => $account['role'],
            'userPhoto'          => $account['photo'],
            'userPhotoDirectory' => $account['photo_directory'],
            'isLoggedIn'         => true,
        ]);

        if ($account['account_type'] === 'user') {
            session()->set('userId', $account['account_id']);
        }

        return redirect()->to($this->homePath());
    }

    public function logout()
    {
        // Hapus semua data session saat logout.
        session()->destroy();

        return redirect()->to('/login')->with('success', 'Anda berhasil logout.');
    }

    private function findAccount(string $email, string $password): ?array
    {
        $user = (new UserModel())
            ->where('email', $email)
            ->whereIn('role', ['administrator', 'kasir'])
            ->first();

        if ($user && password_verify($password, $user['password'])) {
            return [
                'account_type' => 'user',
                'account_id' => (int) $user['id'],
                'name' => $user['name'],
                'email' => $user['email'],
                'role' => $user['role'],
                'photo' => $user['photo'] ?? null,
                'photo_directory' => 'users',
                'is_active' => $user['is_active'],
            ];
        }

        return null;
    }
}
