<?php
class AuthController {
    public function showLogin(): void {
        if (Auth::check()) { redirect('dashboard'); }
        $error = getFlash('error');
        include APP_ROOT . '/views/public/login.php';
    }

    public function login(): void {
        Security::checkCsrf();
        $ip    = Security::getIp();
        $email = strtolower(trim($_POST['email'] ?? ''));
        $pass  = $_POST['password'] ?? '';

        if (!Security::checkLoginRateLimit($ip, $email)) {
            flash('error', 'Too many login attempts. Please wait '.LOGIN_LOCKOUT_MINUTES.' minutes.');
            redirect('login');
        }

        $user = UserModel::findFirstAdminByEmail($email);
        if (!$user || !Security::verifyPassword($pass, $user['password'])) {
            Security::recordLoginAttempt($ip, $email);
            flash('error', 'Invalid email or password.');
            redirect('login');
        }

        if ($user['tenant_status'] === 'suspended') {
            flash('error', 'Your account has been suspended. Please contact support.');
            redirect('login');
        }

        $tenant = [
            'id'            => $user['tenant_id'],
            'slug'          => $user['tenant_slug'],
            'business_name' => $user['business_name'],
            'status'        => $user['tenant_status'],
            'logo'          => $user['tenant_logo'],
        ];

        Security::clearLoginAttempts($ip);
        Auth::login($user, $tenant);
        redirect('dashboard');
    }

    public function showRegister(): void {
        if (Auth::check()) { redirect('dashboard'); }
        $plans = PlanModel::all();
        $error = getFlash('error');
        include APP_ROOT . '/views/public/register.php';
    }

    public function register(): void {
        Security::checkCsrf();
        $name     = Security::sanitize($_POST['name'] ?? '');
        $email    = strtolower(trim($_POST['email'] ?? ''));
        $password = $_POST['password'] ?? '';
        $confirm  = $_POST['confirm_password'] ?? '';
        $bizName  = Security::sanitize($_POST['business_name'] ?? '');

        // Validation
        if (!$name || !$email || !$password || !$bizName) {
            flash('error','All fields are required.');
            redirect('register');
        }
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            flash('error','Invalid email address.');
            redirect('register');
        }
        if (strlen($password) < 8) {
            flash('error','Password must be at least 8 characters.');
            redirect('register');
        }
        if ($password !== $confirm) {
            flash('error','Passwords do not match.');
            redirect('register');
        }
        if (TenantModel::findByEmail($email)) {
            flash('error','An account with this email already exists.');
            redirect('register');
        }

        try {
            db()->beginTransaction();

            // Create tenant
            $slug = Security::makeSlug($bizName) . '-' . substr(bin2hex(random_bytes(3)), 0, 6);
            $tenantId = TenantModel::create([
                'slug'           => $slug,
                'business_name'  => $bizName,
                'business_email' => $email,
                'status'         => 'trial',
                'trial_ends_at'  => date('Y-m-d H:i:s', strtotime('+'.TRIAL_DAYS.' days')),
            ]);

            // Create default location
            $locationId = db()->prepare(
                "INSERT INTO locations (tenant_id,name,code,type) VALUES (?,?,?,?)"
            )  ->execute([$tenantId,'Main Store','MAIN','store']);
            $locationId = (int)db()->lastInsertId();

            // Seed default data (including roles)
            TenantModel::seed($tenantId, $locationId);

            // Get the 'Owner' role ID for this new tenant
            $ownerRoleStmt = db()->prepare("SELECT id FROM roles WHERE tenant_id = ? AND name = 'Owner' LIMIT 1");
            $ownerRoleStmt->execute([$tenantId]);
            $ownerRole = $ownerRoleStmt->fetch();
            $ownerRoleId = $ownerRole ? (int)$ownerRole['id'] : null;

            // Create admin user with both string role and role_id
            $userId = db()->prepare(
                "INSERT INTO users (tenant_id,name,email,password,role,role_id) VALUES (?,?,?,?,?,?)"
            )->execute([$tenantId,$name,$email,Security::hashPassword($password),'Owner',$ownerRoleId]);
            $userId = (int)db()->lastInsertId();

            db()->commit();

            // Auto-login
            $user = UserModel::findByEmail($email, $tenantId);
            $tenant = TenantModel::findById($tenantId);
            Auth::login($user, $tenant);
            redirect('onboarding/business');

        } catch (Exception $e) {
            db()->rollBack();
            flash('error', APP_DEBUG ? $e->getMessage() : 'Registration failed. Please try again.');
            redirect('register');
        }
    }

    public function logout(): void {
        Auth::logout();
        redirect('login');
    }
}
