<?php
// src/Helpers/Auth.php

require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../config/db.php';

class Auth {
    public static function user(): ?array {
        if (!isset($_SESSION['user_id'])) {
            return null;
        }

        $db = Database::getConnection();
        $stmt = $db->prepare("SELECT id, name, email, phone, bio, created_at FROM users WHERE id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $user = $stmt->fetch();
        return $user ?: null;
    }

    public static function check(): bool {
        return isset($_SESSION['user_id']);
    }

    public static function register(string $name, string $email, string $phone, string $password, string $bio = ''): array {
        $db = Database::getConnection();

        // Check if email exists
        $stmtCheck = $db->prepare("SELECT id FROM users WHERE email = ?");
        $stmtCheck->execute([$email]);
        if ($stmtCheck->fetch()) {
            return ['success' => false, 'message' => 'Email address is already registered.'];
        }

        $passwordHash = password_hash($password, PASSWORD_BCRYPT);

        $stmt = $db->prepare("INSERT INTO users (name, email, phone, password_hash, bio) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$name, $email, $phone, $passwordHash, $bio]);
        $userId = (int)$db->lastInsertId();

        // Auto-enroll in Classical Arabic as an introductory course
        $stmtEnroll = $db->prepare("INSERT OR IGNORE INTO enrollments (user_id, course_id, progress, status, completed_modules_json) VALUES (?, 'course-1', 25, 'in_progress', '[0]')");
        $stmtEnroll->execute([$userId]);

        $_SESSION['user_id'] = $userId;
        session_regenerate_id(true);

        return ['success' => true, 'message' => 'Registration successful!'];
    }

    public static function login(string $email, string $password): array {
        $db = Database::getConnection();

        $stmt = $db->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();

        if (!$user || !password_verify($password, $user['password_hash'])) {
            return ['success' => false, 'message' => 'Invalid email address or password.'];
        }

        $_SESSION['user_id'] = $user['id'];
        session_regenerate_id(true);

        return ['success' => true, 'message' => 'Login successful!'];
    }

    public static function logout(): void {
        unset($_SESSION['user_id']);
        session_destroy();
    }

    public static function getCsrfToken(): string {
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }
        return $_SESSION['csrf_token'];
    }

    public static function verifyCsrfToken(?string $token): bool {
        return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token ?? '');
    }
}
