<?php
/**
 * Authentication Helper Functions
 * Login, Register, and Access Control
 */

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/../include/con_data.php';

/**
 * Validate password complexity
 * Requirements: min 8 chars, uppercase, lowercase, number, special char
 */
function validatePassword(string $password): array
{
    $errors = [];

    if (strlen($password) < 8) {
        $errors[] = 'รหัสผ่านต้องมีอย่างน้อย 8 ตัวอักษร';
    }
    if (!preg_match('/[a-z]/', $password)) {
        $errors[] = 'รหัสผ่านต้องมีตัวพิมพ์เล็กอย่างน้อย 1 ตัว';
    }
    if (!preg_match('/[A-Z]/', $password)) {
        $errors[] = 'รหัสผ่านต้องมีตัวพิมพ์ใหญ่อย่างน้อย 1 ตัว';
    }
    if (!preg_match('/[0-9]/', $password)) {
        $errors[] = 'รหัสผ่านต้องมีตัวเลขอย่างน้อย 1 ตัว';
    }
    if (!preg_match('/[!@#$%^&*()_+\-=\[\]{};\':"\\|,.<>\/?]/', $password)) {
        $errors[] = 'รหัสผ่านต้องมีสัญลักษณ์พิเศษอย่างน้อย 1 ตัว (!@#$%^&*...)';
    }

    return $errors;
}

/**
 * Validate email format
 */
function validateEmail(string $email): bool
{
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

/**
 * Check if username exists
 */
function isUsernameExists(PDO $pdo, string $username): bool
{
    $stmt = $pdo->prepare('SELECT COUNT(*) FROM users WHERE username = ?');
    $stmt->execute([$username]);
    return $stmt->fetchColumn() > 0;
}

/**
 * Check if email exists
 */
function isEmailExists(PDO $pdo, string $email): bool
{
    $stmt = $pdo->prepare('SELECT COUNT(*) FROM users WHERE email = ?');
    $stmt->execute([$email]);
    return $stmt->fetchColumn() > 0;
}

/**
 * Register new user
 */
function registerUser(PDO $pdo, string $name, string $username, string $email, string $password, string $role = 'staff'): array
{
    $errors = [];

    // Validate username
    $username = trim($username);
    if (empty($username)) {
        $errors[] = 'กรุณากรอกชื่อผู้ใช้';
    } elseif (strlen($username) < 3 || strlen($username) > 50) {
        $errors[] = 'ชื่อผู้ใช้ต้องมี 3-50 ตัวอักษร';
    } elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
        $errors[] = 'ชื่อผู้ใช้ใช้ได้เฉพาะตัวอักษรภาษาอังกฤษ ตัวเลข และ _';
    } elseif (isUsernameExists($pdo, $username)) {
        $errors[] = 'ชื่อผู้ใช้นี้มีอยู่ในระบบแล้ว';
    }

    // Validate email
    $email = trim($email);
    if (empty($email)) {
        $errors[] = 'กรุณากรอกอีเมล';
    } elseif (!validateEmail($email)) {
        $errors[] = 'รูปแบบอีเมลไม่ถูกต้อง';
    } elseif (isEmailExists($pdo, $email)) {
        $errors[] = 'อีเมลนี้มีอยู่ในระบบแล้ว';
    }

    // Validate password
    $passwordErrors = validatePassword($password);
    if (!empty($passwordErrors)) {
        $errors = array_merge($errors, $passwordErrors);
    }

    // If validation passes, create user
    if (empty($errors)) {
        try {
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare('INSERT INTO users (name, username, email, password, role) VALUES (?, ?, ?, ?, ?)');
            $stmt->execute([$name, $username, $email, $hashedPassword, $role]);

            $userId = $pdo->lastInsertId();

            return ['success' => true, 'message' => 'สมัครสมาชิกสำเร็จ', 'user_id' => $userId];
        } catch (PDOException $e) {
            $errors[] = 'เกิดข้อผิดพลาดในการบันทึกข้อมูล: ' . $e->getMessage();
        }
    }

    return ['success' => false, 'errors' => $errors];
}

/**
 * Login user
 */
function loginUser(PDO $pdo, string $username, string $password): array
{
    $username = trim($username);

    if (empty($username) || empty($password)) {
        return ['success' => false, 'error' => 'กรุณากรอกชื่อผู้ใช้และรหัสผ่าน'];
    }

    $stmt = $pdo->prepare('
        SELECT u.user_id, u.name, u.username, u.email, u.password, u.role, u.status,
               u.shop_id, s.shop_name, s.price_level
        FROM users u
        LEFT JOIN shops s ON u.shop_id = s.shop_id
        WHERE (u.username = ? OR u.email = ?)
    ');
    $stmt->execute([$username, $username]);
    $user = $stmt->fetch();

    if (!$user) {
        return ['success' => false, 'error' => 'ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง'];
    }

    if ($user['status'] != 1) {
        return ['success' => false, 'error' => 'บัญชีนี้ถูกระงับการใช้งาน'];
    }

    if (!password_verify($password, $user['password'])) {
        return ['success' => false, 'error' => 'ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง'];
    }

    // Regenerate session ID to prevent session fixation
    session_regenerate_id(true);

    // Set session data
    $_SESSION['user_id'] = $user['user_id'];
    $_SESSION['name'] = $user['name'];
    $_SESSION['username'] = $user['username'];
    $_SESSION['email'] = $user['email'];
    $_SESSION['role'] = $user['role'];
    $_SESSION['logged_in'] = true;
    $_SESSION['login_time'] = time();

    // Set shop data for multi-store isolation
    $_SESSION['shop_id'] = $user['shop_id'];
    $_SESSION['shop_name'] = $user['shop_name'] ?? '';
    $_SESSION['price_level'] = $user['price_level'] ?? 1;

    // Update last login
    $updateStmt = $pdo->prepare('UPDATE users SET last_login = NOW() WHERE user_id = ?');
    $updateStmt->execute([$user['user_id']]);

    return ['success' => true, 'role' => $user['role']];
}

/**
 * Check if user is logged in
 */
function isLoggedIn(): bool
{
    return isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true;
}

/**
 * Get current user role
 */
function getUserRole(): ?string
{
    return $_SESSION['role'] ?? null;
}

/**
 * Get current user's shop_id
 */
function getShopId(): ?int
{
    return isset($_SESSION['shop_id']) ? (int) $_SESSION['shop_id'] : null;
}

/**
 * Get current user's shop name
 */
function getShopName(): string
{
    return $_SESSION['shop_name'] ?? '';
}

/**
 * Require shop_id - redirect if user has no shop assigned
 */
function requireShop(): void
{
    requireLogin();
    if (empty($_SESSION['shop_id'])) {
        $_SESSION['error_message'] = 'ບັນຊີຂອງທ່ານຍັງບໍ່ໄດ້ກຳນົດຮ້ານ ກະລຸນາຕິດຕໍ່ຜູ້ເບິ່ງແຍງລະບົບ';
        header('Location: /muanjai/login.php');
        exit;
    }
}

/**
 * Require login - redirect if not logged in
 */
function requireLogin(): void
{
    if (!isLoggedIn()) {
        header('Location: /muanjai/login.php');
        exit;
    }
}

/**
 * Require admin role - redirect if not admin
 */
function requireAdmin(): void
{
    requireLogin();

    if (getUserRole() !== 'superadmin' && getUserRole() !== 'manager') {
        $_SESSION['error_message'] = 'คุณไม่มีสิทธิ์เข้าถึงหน้านี้';
        header('Location: /muanjai/user/dashboard.php');
        exit;
    }
}

/**
 * Logout user
 */
function logoutUser(): void
{
    // Unset all session variables
    $_SESSION = [];

    // Delete session cookie
    if (ini_get('session.use_cookies')) {
        $params = session_get_cookie_params();
        setcookie(
            session_name(),
            '',
            time() - 42000,
            $params['path'],
            $params['domain'],
            $params['secure'],
            $params['httponly']
        );
    }

    // Destroy session
    session_destroy();
}

/**
 * Sanitize input string
 */
function sanitizeInput(string $input): string
{
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}
?>