<?php
/**
 * Flexi Access Bank - Helper Functions
 * Core utility functions for the banking platform
 */

require_once 'config.php';

// Load Composer autoloader (PHPMailer + any other packages)
if (file_exists(__DIR__ . '/vendor/autoload.php')) {
    require_once __DIR__ . '/vendor/autoload.php';
}

//use PHPMailer\PHPMailer\PHPMailer;
//use PHPMailer\PHPMailer\SMTP;
//use PHPMailer\PHPMailer\Exception as MailException;\
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';

// Database Connection
function getDB() {
    static $db = null;
    if ($db === null) {
        $db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        if ($db->connect_error) {
            die('Connection failed: ' . $db->connect_error);
        }
        $db->set_charset('utf8mb4');
    }
    return $db;
}

// ============================================================
// Authentication Functions
// ============================================================

function isLoggedIn() {
    return isset($_SESSION['user_id']) && $_SESSION['user_type'] === 'user';
}

function isAdminLoggedIn() {
    return isset($_SESSION['admin_id']) && $_SESSION['user_type'] === 'admin';
}

function requireAuth() {
    if (!isLoggedIn()) {
        header('Location: index.php');
        exit();
    }
}
function get_option(string $key, $default = '') {
    global $db;
    $stmt = $db->prepare("SELECT option_value FROM options WHERE option_key = ? LIMIT 1");
    if (!$stmt) return $default;
    $stmt->bind_param("s", $key);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $stmt->close();
    return $row['option_value'] ?? $default;
}

function requireAdminAuth() {
    if (!isAdminLoggedIn()) {
        header('Location: admin/index.php');
        exit();
    }
}

function getCurrentUser() {
    if (!isLoggedIn()) return null;
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->bind_param('i', $_SESSION['user_id']);
    $stmt->execute();
    $result = $stmt->get_result();
    return $result->fetch_assoc();
}

function getCurrentAdmin() {
    if (!isAdminLoggedIn()) return null;
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM admin_users WHERE id = ?");
    $stmt->bind_param('i', $_SESSION['admin_id']);
    $stmt->execute();
    $result = $stmt->get_result();
    return $result->fetch_assoc();
}

// ============================================================
// Formatting Functions
// ============================================================

function formatCurrency($amount) {
    return CURRENCY_SYMBOL . number_format($amount, 2);
}

function formatDate($date) {
    return date('M d, Y h:i A', strtotime($date));
}

function formatDateShort($date) {
    return date('M d, Y', strtotime($date));
}

function maskAccount($account) {
    return '****' . substr($account, -4);
}

function maskCard($cardNumber) {
    return '**** **** **** ' . substr($cardNumber, -4);
}

function generateAccountNumber() {
    return '10' . rand(10000000, 99999999);
}

function generateReference() {
    return 'FLEXI' . date('Y') . strtoupper(bin2hex(random_bytes(5)));
}

function generateTicketNumber() {
    return 'TKT-' . date('Y') . strtoupper(substr(md5(uniqid()), 0, 8));
}

// ============================================================
// Security Functions
// ============================================================

function hashPassword($password) {
    return password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
}

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

function generateOTP() {
    return str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
}

function isLockedOut($user) {
    if ($user['locked_until'] && strtotime($user['locked_until']) > time()) {
        return true;
    }
    return false;
}

function logActivity($action, $description = '', $userId = null, $adminId = null) {
    $db = getDB();
    $ip = $_SERVER['REMOTE_ADDR'] ?? null;
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? null;
    $stmt = $db->prepare(
        "INSERT INTO activity_logs (user_id, admin_id, action, description, ip_address, user_agent)
         VALUES (?, ?, ?, ?, ?, ?)"
    );
    $stmt->bind_param('iissss', $userId, $adminId, $action, $description, $ip, $userAgent);
    $stmt->execute();
}

function logLogin($userId, $type = 'user', $status = 'success') {
    $db = getDB();
    $ip = $_SERVER['REMOTE_ADDR'] ?? null;
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? null;
    $stmt = $db->prepare(
        "INSERT INTO login_history (user_id, login_type, ip_address, user_agent, status)
         VALUES (?, ?, ?, ?, ?)"
    );
    $stmt->bind_param('issss', $userId, $type, $ip, $userAgent, $status);
    $stmt->execute();
}

// ============================================================
// Notification Functions
// ============================================================

function createNotification($userId, $title, $message, $type = 'info', $relatedId = null, $relatedType = null) {
    $db = getDB();
    $stmt = $db->prepare(
        "INSERT INTO notifications (user_id, title, message, type, related_id, related_type)
         VALUES (?, ?, ?, ?, ?, ?)"
    );
    $stmt->bind_param('isssis', $userId, $title, $message, $type, $relatedId, $relatedType);
    $stmt->execute();
}

function getUnreadNotifications($userId) {
    $db = getDB();
    $stmt = $db->prepare(
        "SELECT * FROM notifications WHERE user_id = ? AND is_read = 0
         ORDER BY created_at DESC LIMIT 10"
    );
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}

function getNotificationCount($userId) {
    $db = getDB();
    $stmt = $db->prepare(
        "SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = 0"
    );
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc()['count'];
}

// ============================================================
// Transaction Functions
// ============================================================

function createTransaction($data) {
    $db = getDB();
    $stmt = $db->prepare(
        "INSERT INTO transactions
            (user_id, transaction_type, amount, currency, description, reference_number,
             beneficiary_name, beneficiary_account, beneficiary_bank, beneficiary_bank_code,
             beneficiary_swift, beneficiary_iban, beneficiary_routing, beneficiary_country,
             transfer_type, transfer_mode, require_imf, require_cot, require_otp, ip_address)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
    );
    $stmt->bind_param(
        'isdsssssssssssssssis',
        $data['user_id'], $data['transaction_type'], $data['amount'], $data['currency'],
        $data['description'], $data['reference_number'], $data['beneficiary_name'],
        $data['beneficiary_account'], $data['beneficiary_bank'], $data['beneficiary_bank_code'],
        $data['beneficiary_swift'], $data['beneficiary_iban'], $data['beneficiary_routing'],
        $data['beneficiary_country'], $data['transfer_type'], $data['transfer_mode'],
        $data['require_imf'], $data['require_cot'], $data['require_otp'], $data['ip_address']
    );
    $stmt->execute();
    return $db->insert_id;
}

function getTransactions($userId, $limit = 50) {
    $db = getDB();
    $stmt = $db->prepare(
        "SELECT * FROM transactions WHERE user_id = ? ORDER BY created_at DESC LIMIT ?"
    );
    $stmt->bind_param('ii', $userId, $limit);
    $stmt->execute();
    return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}

function getTransactionStats($userId) {
    global $db;
    
    $stmt = $db->prepare("
        SELECT 
            SUM(CASE WHEN transaction_type = 'credit' AND status = 'completed' THEN amount ELSE 0 END) as total_credits,
            SUM(CASE WHEN transaction_type = 'transfer' AND status = 'completed' THEN amount ELSE 0 END) as total_debits,
            COUNT(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_count
        FROM transactions 
        WHERE user_id = ?
    ");
    
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}

// ============================================================
// Card Functions
// ============================================================

function getUserCards($userId) {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM cards WHERE user_id = ?");
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}

// ============================================================
// Bank Functions
// ============================================================

function getAllBanks() {
    $db = getDB();
    return $db->query("SELECT * FROM banks WHERE status = 1 ORDER BY bank_name");
}

// ============================================================
// Settings Functions
// ============================================================

function getSetting($key) {
    $db = getDB();
    $stmt = $db->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
    $stmt->bind_param('s', $key);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($row = $result->fetch_assoc()) {
        return $row['setting_value'];
    }
    return null;
}

function updateSetting($key, $value) {
    $db = getDB();
    $stmt = $db->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = ?");
    $stmt->bind_param('ss', $value, $key);
    return $stmt->execute();
}

// ============================================================
// Admin Helper Functions
// ============================================================

function getAllUsers() {
    $db = getDB();
    return $db->query("SELECT * FROM users ORDER BY created_at DESC");
}

function getUserCount() {
    $db = getDB();
    return $db->query("SELECT COUNT(*) as count FROM users")->fetch_assoc()['count'];
}

function getTotalBalance() {
    $db = getDB();
    return $db->query("SELECT COALESCE(SUM(account_balance), 0) as total FROM users")
              ->fetch_assoc()['total'];
}

function getTransactionCount() {
    $db = getDB();
    return $db->query("SELECT COUNT(*) as count FROM transactions")->fetch_assoc()['count'];
}

function getPendingTickets() {
    $db = getDB();
    return $db->query("SELECT COUNT(*) as count FROM support_tickets WHERE status = 'open'")
              ->fetch_assoc()['count'];
}

function getCryptoWallets() {
    $db = getDB();
    return $db->query("SELECT * FROM crypto_wallets WHERE is_active = 1");
}

function getSupportTickets($status = null) {
    $db = getDB();
    if ($status) {
        $stmt = $db->prepare(
            "SELECT t.*, u.first_name, u.last_name, u.email
             FROM support_tickets t
             JOIN users u ON t.user_id = u.id
             WHERE t.status = ?
             ORDER BY t.created_at DESC"
        );
        $stmt->bind_param('s', $status);
        $stmt->execute();
        return $stmt->get_result();
    }
    return $db->query(
        "SELECT t.*, u.first_name, u.last_name, u.email
         FROM support_tickets t
         JOIN users u ON t.user_id = u.id
         ORDER BY t.created_at DESC"
    );
}

// ============================================================
// PHPMailer Email Function
// ============================================================

/**
 * Send an HTML email via PHPMailer using SMTP.
 *
 * @param string       $to      Recipient email address
 * @param string       $subject Email subject
 * @param string       $body    HTML email body
 * @param string|null  $toName  Optional display name for the recipient
 * @param array        $extra   Optional: ['reply_to' => email, 'cc' => email, 'attachments' => [path, ...]]
 * @return bool
 */
function sendMail(string $to, string $subject, string $body, string $toName = '', array $extra = []): bool
{
    // Verify PHPMailer is available (via Composer autoload)
    if (!class_exists(PHPMailer::class)) {
        error_log('[FlexiAccess Mail] PHPMailer not found. Run: composer install');
        return false;
    }

    $mail = new PHPMailer(true); // true = throw exceptions

    try {
        // ── Server configuration ──────────────────────────────
        $mail->isSMTP();
        $mail->Host        = SMTP_HOST;
        $mail->SMTPAuth    = true;
        $mail->Username    = SMTP_USER;
        $mail->Password    = SMTP_PASS;
        $mail->Port        = SMTP_PORT;

        // Encryption: use PHPMailer constants (not raw strings)
        if (SMTP_ENCRYPTION === 'ssl') {
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        } elseif (SMTP_ENCRYPTION === 'tls') {
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        }

        // ── Sender ────────────────────────────────────────────
        $mail->setFrom(SMTP_FROM_EMAIL, SMTP_FROM_NAME);

        // ── Recipient ─────────────────────────────────────────
        $mail->addAddress($to, $toName ?: $to);

        // Optional Reply-To
        if (!empty($extra['reply_to'])) {
            $mail->addReplyTo($extra['reply_to'], $extra['reply_to_name'] ?? '');
        }

        // Optional CC
        if (!empty($extra['cc'])) {
            foreach ((array)$extra['cc'] as $cc) {
                $mail->addCC($cc);
            }
        }

        // Optional attachments
        if (!empty($extra['attachments'])) {
            foreach ((array)$extra['attachments'] as $path) {
                if (file_exists($path)) {
                    $mail->addAttachment($path);
                }
            }
        }

        // ── Content ───────────────────────────────────────────
        $mail->isHTML(true);
        $mail->CharSet = 'UTF-8';
        $mail->Subject = $subject;
        $mail->Body    = buildEmailTemplate($subject, $body);
        $mail->AltBody = strip_tags(str_replace(['<br>', '<br/>', '<br />'], "\n", $body));

        $mail->send();
        return true;

    } catch (MailException $e) {
        error_log('[FlexiAccess Mail] Failed to send to ' . $to . ': ' . $mail->ErrorInfo);
        return false;
    }
}

/**
 * Wrap the raw HTML body in a branded email template.
 */
function buildEmailTemplate(string $subject, string $htmlBody): string
{
    $siteName = defined('SITE_NAME') ? SITE_NAME : 'Flexi Access Bank';
    $year     = date('Y');

    return <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{$subject}</title>
</head>
<body style="margin:0;padding:0;background:#f4f4f8;font-family:'Segoe UI',Arial,sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f4f8;padding:40px 0;">
    <tr><td align="center">
      <table width="600" cellpadding="0" cellspacing="0"
             style="background:#ffffff;border-radius:12px;overflow:hidden;
                    box-shadow:0 4px 20px rgba(0,0,0,0.08);max-width:600px;width:100%;">

        <!-- Header -->
        <tr>
          <td style="background:linear-gradient(135deg,#DC2626,#991B1B);padding:32px 40px;text-align:center;">
            <h1 style="margin:0;color:#ffffff;font-size:22px;font-weight:800;letter-spacing:-0.02em;">
              &#9670; {$siteName}
            </h1>
            <p style="margin:6px 0 0;color:rgba(255,255,255,0.75);font-size:13px;letter-spacing:0.05em;">
              BANKING WITHOUT BOUNDARIES
            </p>
          </td>
        </tr>

        <!-- Body -->
        <tr>
          <td style="padding:40px;color:#1f1f1f;font-size:15px;line-height:1.7;">
            {$htmlBody}
          </td>
        </tr>

        <!-- Divider -->
        <tr>
          <td style="padding:0 40px;">
            <hr style="border:none;border-top:1px solid #e5e7eb;margin:0;">
          </td>
        </tr>

        <!-- Footer -->
        <tr>
          <td style="padding:28px 40px;text-align:center;">
            <p style="margin:0 0 8px;font-size:12px;color:#9ca3af;">
              This email was sent by <strong>{$siteName}</strong>.
              Please do not reply directly to this email.
            </p>
            <p style="margin:0;font-size:11px;color:#d1d5db;">
              &copy; {$year} {$siteName}. All rights reserved. Member FDIC.
            </p>
          </td>
        </tr>

      </table>
    </td></tr>
  </table>
</body>
</html>
HTML;
}

// ============================================================
// Specialised Email Helpers
// ============================================================

/**
 * Send a welcome email to a newly registered user.
 */
function sendWelcomeEmail(array $user): bool
{
    $name    = e($user['first_name'] . ' ' . $user['last_name']);
    $account = e($user['account_number']);
    $type    = ucfirst(e($user['account_type']));
    $loginUrl = defined('BASE_URL') ? BASE_URL . 'login.php' : 'login.php';

    $body = <<<HTML
<h2 style="color:#DC2626;margin:0 0 16px;">Welcome to Flexi Access Bank!</h2>
<p>Hi <strong>{$name}</strong>,</p>
<p>Thank you for opening your account with us. Your account has been successfully created.</p>
<table width="100%" cellpadding="12" cellspacing="0"
       style="background:#f9fafb;border-radius:8px;margin:24px 0;font-size:14px;">
  <tr>
    <td style="width:50%;color:#6b7280;">Account Number</td>
    <td style="font-weight:700;color:#111;">{$account}</td>
  </tr>
  <tr style="background:#f3f4f6;">
    <td style="color:#6b7280;">Account Type</td>
    <td style="font-weight:700;color:#111;">{$type}</td>
  </tr>
  <tr>
    <td style="color:#6b7280;">Status</td>
    <td style="font-weight:700;color:#10B981;">Active</td>
  </tr>
</table>
<p>To get started, please complete your KYC verification so you can access all features,
   including transfers and investments.</p>
<p style="text-align:center;margin:32px 0;">
  <a href="{$loginUrl}"
     style="background:#DC2626;color:#fff;padding:14px 32px;border-radius:8px;
            text-decoration:none;font-weight:700;font-size:15px;">
    Sign In to Your Account
  </a>
</p>
<p style="color:#6b7280;font-size:13px;">
  If you did not create this account, please contact our support team immediately at
  <a href="mailto:support@flexiaccess.site" style="color:#DC2626;">support@flexiaccess.site</a>.
</p>
HTML;

    return sendMail($user['email'], 'Welcome to ' . SITE_NAME . ' — Your Account Is Ready', $body, $name);
}

/**
 * Send a transaction receipt/notification email.
 */
function sendTransactionEmail(array $user, array $tx): bool
{
    $name      = e($user['first_name'] . ' ' . $user['last_name']);
    $type      = ucfirst(e($tx['transaction_type']));
    $amount    = formatCurrency($tx['amount']);
    $ref       = e($tx['reference_number']);
    $status    = ucfirst(e($tx['status']));
    $date      = formatDate($tx['created_at']);
    $typeColor = $tx['transaction_type'] === 'credit' ? '#10B981' : '#DC2626';
    $typeSymbol = $tx['transaction_type'] === 'credit' ? '+' : '-';

    $body = <<<HTML
<h2 style="color:#DC2626;margin:0 0 16px;">Transaction {$status}</h2>
<p>Hi <strong>{$name}</strong>,</p>
<p>A transaction has been processed on your account. Details below:</p>
<table width="100%" cellpadding="12" cellspacing="0"
       style="background:#f9fafb;border-radius:8px;margin:24px 0;font-size:14px;">
  <tr>
    <td style="width:50%;color:#6b7280;">Type</td>
    <td style="font-weight:700;color:{$typeColor};">{$type}</td>
  </tr>
  <tr style="background:#f3f4f6;">
    <td style="color:#6b7280;">Amount</td>
    <td style="font-weight:800;font-size:18px;color:{$typeColor};">{$typeSymbol}{$amount}</td>
  </tr>
  <tr>
    <td style="color:#6b7280;">Reference</td>
    <td style="font-weight:700;color:#111;font-family:monospace;">{$ref}</td>
  </tr>
  <tr style="background:#f3f4f6;">
    <td style="color:#6b7280;">Status</td>
    <td style="font-weight:700;color:#111;">{$status}</td>
  </tr>
  <tr>
    <td style="color:#6b7280;">Date</td>
    <td style="color:#111;">{$date}</td>
  </tr>
</table>
<p style="color:#6b7280;font-size:13px;">
  If you did not authorise this transaction, please contact support immediately at
  <a href="mailto:support@flexiaccess.site" style="color:#DC2626;">support@flexiaccess.site</a>
  or call our 24/7 helpline.
</p>
HTML;

    return sendMail(
        $user['email'],
        SITE_NAME . ': Transaction ' . $status . ' — ' . $amount,
        $body,
        $name
    );
}

/**
 * Send a password-reset link.
 */
function sendPasswordResetEmail(string $email, string $token, string $userName = ''): bool
{
    $baseUrl  = defined('BASE_URL') ? BASE_URL : '';
    $resetUrl = $baseUrl . 'reset-password.php?token=' . urlencode($token);

    $body = <<<HTML
<h2 style="color:#DC2626;margin:0 0 16px;">Reset Your Password</h2>
<p>Hi{$userName},</p>
<p>We received a request to reset the password for your Flexi Access Bank account.</p>
<p style="text-align:center;margin:32px 0;">
  <a href="{$resetUrl}"
     style="background:#DC2626;color:#fff;padding:14px 32px;border-radius:8px;
            text-decoration:none;font-weight:700;font-size:15px;">
    Reset My Password
  </a>
</p>
<p style="color:#6b7280;font-size:13px;">
  This link will expire in <strong>60 minutes</strong>.
  If you did not request a password reset, you can safely ignore this email — your account
  remains secure.
</p>
<p style="color:#9ca3af;font-size:12px;word-break:break-all;">
  Or copy this link: {$resetUrl}
</p>
HTML;

    return sendMail($email, SITE_NAME . ': Password Reset Request', $body, $userName);
}

/**
 * Send an OTP code email.
 */
function sendOTPEmail(string $email, string $otp, string $purpose = 'login', string $userName = ''): bool
{
    $purposeLabel = match ($purpose) {
        'login'          => 'Login Verification',
        'transfer'       => 'Transfer Authorisation',
        'password_reset' => 'Password Reset',
        'email_verify'   => 'Email Verification',
        default          => 'Verification',
    };

    $body = <<<HTML
<h2 style="color:#DC2626;margin:0 0 16px;">{$purposeLabel} Code</h2>
<p>Hi{$userName},</p>
<p>Your one-time verification code is:</p>
<div style="text-align:center;margin:32px 0;">
  <span style="display:inline-block;background:#f9fafb;border:2px dashed #DC2626;
               border-radius:12px;padding:20px 40px;font-size:40px;font-weight:900;
               letter-spacing:10px;color:#DC2626;font-family:monospace;">
    {$otp}
  </span>
</div>
<p style="color:#6b7280;font-size:13px;">
  This code is valid for <strong>10 minutes</strong> and can only be used once.
  Never share this code with anyone — Flexi Access Bank staff will never ask for it.
</p>
HTML;

    return sendMail($email, SITE_NAME . ': Your ' . $purposeLabel . ' Code', $body, $userName);
}

/**
 * Send a contact-form enquiry to the bank's support inbox.
 */
function sendContactEmail(
    string $senderName,
    string $senderEmail,
    string $senderPhone,
    string $subject,
    string $message
): bool {
    $safeN = e($senderName);
    $safeE = e($senderEmail);
    $safeP = e($senderPhone);
    $safeS = e($subject);
    $safeM = nl2br(e($message));
    $date  = date('D, d M Y H:i:s T');

    $body = <<<HTML
<h2 style="color:#DC2626;margin:0 0 16px;">New Contact Form Enquiry</h2>
<table width="100%" cellpadding="12" cellspacing="0"
       style="background:#f9fafb;border-radius:8px;margin:0 0 24px;font-size:14px;">
  <tr>
    <td style="width:35%;color:#6b7280;font-weight:600;">Name</td>
    <td style="font-weight:700;color:#111;">{$safeN}</td>
  </tr>
  <tr style="background:#f3f4f6;">
    <td style="color:#6b7280;font-weight:600;">Email</td>
    <td><a href="mailto:{$safeE}" style="color:#DC2626;">{$safeE}</a></td>
  </tr>
  <tr>
    <td style="color:#6b7280;font-weight:600;">Phone</td>
    <td style="color:#111;">{$safeP}</td>
  </tr>
  <tr style="background:#f3f4f6;">
    <td style="color:#6b7280;font-weight:600;">Subject</td>
    <td style="font-weight:700;color:#111;">{$safeS}</td>
  </tr>
  <tr>
    <td style="color:#6b7280;font-weight:600;">Received</td>
    <td style="color:#111;">{$date}</td>
  </tr>
</table>
<div style="background:#fff;border:1px solid #e5e7eb;border-radius:8px;padding:20px;">
  <p style="margin:0 0 8px;font-weight:700;color:#374151;">Message:</p>
  <p style="margin:0;color:#1f1f1f;line-height:1.7;">{$safeM}</p>
</div>
HTML;

    // Send to support inbox, with reply-to set to the sender
    return sendMail(
        SITE_EMAIL,
        '[Contact Form] ' . $subject . ' — ' . $senderName,
        $body,
        SITE_NAME . ' Support',
        ['reply_to' => $senderEmail, 'reply_to_name' => $senderName]
    );
}

/**
 * Send an auto-reply acknowledgement to a contact form submitter.
 */
function sendContactAutoReply(string $toEmail, string $toName, string $subject): bool
{
    $safeName = e($toName);
    $safeSubj = e($subject);

    $body = <<<HTML
<h2 style="color:#DC2626;margin:0 0 16px;">We've Received Your Message</h2>
<p>Hi <strong>{$safeName}</strong>,</p>
<p>Thank you for reaching out to Flexi Access Bank. We have received your enquiry
   regarding <strong>"{$safeSubj}"</strong> and a member of our team will get back
   to you within <strong>24 hours</strong>.</p>
<p>In the meantime, you can:</p>
<ul style="color:#374151;line-height:2;">
  <li>Visit our <a href="https://flexiaccess.site/index.php#faq" style="color:#DC2626;">FAQ page</a></li>
  <li>Log in to <a href="https://flexiaccess.site/login.php" style="color:#DC2626;">your account</a></li>
  <li>Call our 24/7 helpline at <strong>+1 (800) FLEXI-00</strong></li>
</ul>
<p>Reference: <strong style="font-family:monospace;">#CNT-{$safeSubj}</strong></p>
<p style="color:#6b7280;font-size:13px;margin-top:24px;">
  Please do not reply to this email. If you need further assistance, use our
  <a href="https://flexiaccess.site/support.php" style="color:#DC2626;">support portal</a>.
</p>
HTML;

    return sendMail(
        $toEmail,
        'We received your message — ' . SITE_NAME,
        $body,
        $toName
    );
}

// ============================================================
// Output Escaping
// ============================================================

function e($string) {
    return htmlspecialchars($string ?? '', ENT_QUOTES, 'UTF-8');
}

// ============================================================
// Flash Messages
// ============================================================

function setFlash($message, $type = 'success') {
    $_SESSION['flash'] = ['message' => $message, 'type' => $type];
}

function getFlash() {
    if (isset($_SESSION['flash'])) {
        $flash = $_SESSION['flash'];
        unset($_SESSION['flash']);
        return $flash;
    }
    return null;
}
function getUserTransferFee($userId, $transferType, $transferAmount = 0) {
    $db = getDB();

    // Get user settings
    $stmt = $db->prepare("SELECT transfer_fee_enabled, transfer_fee_type, 
        transfer_fee_local, transfer_fee_international, transfer_fee_internal 
        FROM users WHERE id = ?");
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();

    if (!$user) {
        // Fallback to global settings
        return getGlobalTransferFee($transferType, $transferAmount);
    }

    // Check if user has custom fees enabled
    if (!empty($user['transfer_fee_enabled'])) {
        $feeType = $user['transfer_fee_type'] ?? 'flat';
        $feeField = 'transfer_fee_' . $transferType;
        $feeValue = floatval($user[$feeField] ?? 0);

        // If user fee is 0, they might want free transfers - respect that
        // But if it's truly not set, fall back to global
        // Since we default to 0.00, we assume 0 means free or use global
        // To distinguish: if fee_enabled=1, use user value even if 0

        $calculatedFee = $feeValue;
        if ($feeType === 'percentage') {
            $calculatedFee = ($transferAmount * $feeValue) / 100;
        }

        return [
            'fee' => $calculatedFee,
            'type' => $feeType,
            'source' => 'user',
            'raw_value' => $feeValue
        ];
    }

    // Use global settings
    return getGlobalTransferFee($transferType, $transferAmount);
}

/**
 * Get global transfer fee from settings table
 */
function getGlobalTransferFee($transferType, $transferAmount = 0) {
    $db = getDB();

    $settingKey = 'transfer_fee_' . $transferType;
    $stmt = $db->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
    $stmt->bind_param('s', $settingKey);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();

    $feeValue = floatval($result['setting_value'] ?? 0);

    // Global fees are always flat in your current schema
    return [
        'fee' => $feeValue,
        'type' => 'flat',
        'source' => 'global',
        'raw_value' => $feeValue
    ];
}

/**
 * Get effective transfer limits for a user
 * Returns array with limits and source
 */
function getUserTransferLimits($userId) {
    $db = getDB();

    $stmt = $db->prepare("SELECT transfer_limit_enabled, max_single_transfer, 
        transfer_limit_single, transfer_limit_daily 
        FROM users WHERE id = ?");
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();

    if ($user && !empty($user['transfer_limit_enabled'])) {
        return [
            'max_single' => floatval($user['max_single_transfer']) > 0 ? floatval($user['max_single_transfer']) : null,
            'single_limit' => floatval($user['transfer_limit_single']) > 0 ? floatval($user['transfer_limit_single']) : null,
            'daily_limit' => floatval($user['transfer_limit_daily']) > 0 ? floatval($user['transfer_limit_daily']) : null,
            'source' => 'user'
        ];
    }

    // Get global limits
    $settings = $db->query("SELECT setting_key, setting_value FROM settings 
        WHERE setting_key IN ('max_single_transfer','daily_transfer_limit')");
    $global = [];
    while ($row = $settings->fetch_assoc()) {
        $global[$row['setting_key']] = floatval($row['setting_value']);
    }

    return [
        'max_single' => $global['max_single_transfer'] ?? 25000,
        'single_limit' => $global['daily_transfer_limit'] ?? 50000,
        'daily_limit' => $global['daily_transfer_limit'] ?? 50000,
        'source' => 'global'
    ];
}

/**
 * Calculate total fee for a transfer
 * Example usage in your transfer processing code:
 */
function calculateTransferFee($userId, $transferType, $amount) {
    $feeInfo = getUserTransferFee($userId, $transferType, $amount);

    // Log for transparency
    error_log("Transfer fee for user {$userId}: " . json_encode($feeInfo));

    return $feeInfo['fee'];
}
