<?php
session_start();
require_once __DIR__ . '/includes/db.php';

/**
 * Check if a user is logged in
 */
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

/**
 * Log in a user by setting session
 */
function loginUser($user_id, $first_name) {
    $_SESSION['user_id'] = $user_id;
    $_SESSION['user_name'] = $first_name;
}

/**
 * Log out user and destroy session
 */
function logoutUser() {
    session_unset();
    session_destroy();
}

/**
 * Generate a random OTP (6-digit)
 */
function generateOTP() {
    return random_int(100000, 999999);
}

/**
 * Send OTP or notification email
 * 
 * @param string $to Recipient email
 * @param string $subject Email subject
 * @param string $body Email body
 * @return bool True if sent successfully
 */
function sendEmail($to, $subject, $body) {
    $headers = "From: no-reply@demobank.com\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
    return mail($to, $subject, $body, $headers);
}

/**
 * Verify user OTP
 * 
 * @param int $user_id
 * @param string $otp_token
 * @return bool
 */
function verifyOTP($user_id, $otp_token) {
    global $conn;
    $stmt = $conn->prepare("SELECT otp, otp_used FROM users WHERE id = ? AND otp = ?");
    $stmt->bind_param("is", $user_id, $otp_token);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();

    if ($result && $result['otp_used'] == 0) {
        // Mark OTP as used
        $stmt = $conn->prepare("UPDATE users SET otp_used = 1, otp = NULL WHERE id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        return true;
    }
    return false;
}

/**
 * Require user login for page access
 */
function requireLogin() {
    if (!isLoggedIn()) {
        header("Location: ../auth/login.php");
        exit();
    }
}

/**
 * Get user details by ID
 */
function getUser($user_id) {
    global $conn;
    $stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}