<?php
class Auth extends Controller {
    private $loginModel;

    public function __construct() {
        if (session_status() == PHP_SESSION_NONE) session_start();
        $this->loginModel = $this->logic("Login_model");
    }

    // GET -> show login page (your UI file). POST -> process login
    public function index() {
        // if POST, process
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $email = $_POST['email'] ?? '';
            $password = $_POST['password'] ?? '';

            $user = $this->loginModel->findByEmail($email);
            if ($user && password_verify($password, $user['password'])) {
                // success
                $_SESSION['user'] = $user;
                header("Location: " . APP_PATH . "employees");
                exit;
            } else {
                // login failed — set flash then show UI
                $_SESSION['auth_error'] = "Email or password incorrect";
                // render login view (UI not changed)
                $this->display("auth/login");
                return;
            }
        }

        // GET => show login UI
        $this->display("auth/login");
    }

    // Signup page — UI and process in same route
    public function signup() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $username = $_POST['username'] ?? ($_POST['name'] ?? '');
            $email = $_POST['email'] ?? '';
            $password = $_POST['password'] ?? '';
            $confirm  = $_POST['confirm'] ?? $_POST['password_confirm'] ?? '';

            // basic checks
            if ($password !== $confirm) {
                $_SESSION['auth_error'] = "Password confirmation does not match.";
                $this->display("auth/signup");
                return;
            }

            // check duplicate
            if ($this->loginModel->findByEmail($email)) {
                $_SESSION['auth_error'] = "Email already registered.";
                $this->display("auth/signup");
                return;
            }

            $hash = password_hash($password, PASSWORD_BCRYPT);
            $this->loginModel->createUser($username, $email, $hash);

            // success -> redirect to login
            $_SESSION['auth_success'] = "Account created. Please login.";
            header("Location: " . APP_PATH . "auth");
            exit;
        }

        // GET => show signup UI
        $this->display("auth/signup");
    }

    public function logout() {
        if (session_status() == PHP_SESSION_NONE) session_start();
        session_destroy();
        header("Location: " . APP_PATH . "auth");
        exit;
    }
}
?>
  