<?php

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . "/db.php";
require_once __DIR__ . "/currency_helper.php";

/**
 * =========================================
 * PASSWORD HELPERS
 * =========================================
 */

function hashPassword($password) {
    return password_hash($password, PASSWORD_BCRYPT);
}

function verifyPassword($password, $hash) {
    return password_verify($password, $hash);
}

/**
 * =========================================
 * VALIDATION HELPERS
 * =========================================
 */

function isValidEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

/**
 * =========================================
 * TOKEN GENERATOR
 * =========================================
 */

function generateToken($length = 32) {
    return bin2hex(random_bytes($length));
}

/**
 * =========================================
 * ACCOUNT NUMBER GENERATOR (SAFE)
 * =========================================
 */

function generateAccountNumber($conn = null) {

    if (!$conn) {
        $conn = db();
    }

    do {
        $number = (string)mt_rand(1000000000, 9999999999);

        $stmt = $conn->prepare("
            SELECT id 
            FROM accounts 
            WHERE account_number = ?
        ");

        if (!$stmt) {
            die("SQL ERROR (generateAccountNumber): " . $conn->error);
        }

        $stmt->bind_param("s", $number);
        $stmt->execute();
        $stmt->store_result();

    } while ($stmt->num_rows > 0);

    return $number;
}

/**
 * =========================================
 * CREATE ACCOUNT FOR USER (CORE BANKING)
 * =========================================
 */

function createAccountForUser($conn, $user_id, $account_type, $currency, $account_number) {

    $stmt = $conn->prepare("
        INSERT INTO accounts 
        (user_id, account_number, account_type, balance, currency, status)
        VALUES (?, ?, ?, 0.00, ?, 'active')
    ");

    if (!$stmt) {
        die("ACCOUNT INSERT ERROR: " . $conn->error);
    }

    $stmt->bind_param(
        "isss",
        $user_id,
        $account_number,
        $account_type,
        $currency
    );

    return $stmt->execute();
}

/**
 * =========================================
 * CURRENCY
 * =========================================
 */

function displayAmount($amount, $currencyCode) {
    return formatCurrency($amount, $currencyCode);
}

/**
 * =========================================
 * SESSION FLASH MESSAGES
 * =========================================
 */

function flashMessage($name, $message = '') {

    if ($message) {
        $_SESSION[$name] = $message;
        return true;
    }

    if (isset($_SESSION[$name])) {
        $msg = $_SESSION[$name];
        unset($_SESSION[$name]);
        return $msg;
    }

    return null;
}

/**
 * =========================================
 * SECURITY HELPERS
 * =========================================
 */

function sanitizeInput($input) {
    return htmlspecialchars(strip_tags(trim($input)), ENT_QUOTES, 'UTF-8');
}

function redirect($url) {
    header("Location: $url");
    exit;
}
function renderLayout($title, $content, $conn = null) {
    include __DIR__ . "/../components/layout.php";
}
function createNotification($conn, $user_id, $message) {
    $stmt = $conn->prepare("
        INSERT INTO notifications (user_id, message, is_read, created_at)
        VALUES (?, ?, 0, NOW())
    ");
    if ($stmt) {
        $stmt->bind_param("is", $user_id, $message);
        $stmt->execute();
        $stmt->close();
    }
}