<?php
/**
 * Unified Bank Email Helper
 * =========================
 * Single entry point for all email sending across the application.
 * Uses PHP's native mail() — no external dependencies.
 *
 * Requires: settings-helper.php (auto-prepended by .htaccess)
 */

// ── Security: sanitise header values ──────────────────────────────
function _email_sanitise($value) {
    return trim(str_replace(["\r", "\n", "\0", "%0a", "%0d"], '', $value));
}

// ── Validation ────────────────────────────────────────────────────
function _email_valid($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

// ── Get bank defaults from settings ───────────────────────────────
function _bank_defaults() {
    $siteUrl = getSetting('site_url', '');
    if (empty($siteUrl)) {
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $siteUrl = $protocol . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
    }
    $siteUrl = rtrim($siteUrl, '/');

    $logoPath = getSetting('logo_path', 'logo.png');
    $logoUrl = (strpos($logoPath, 'http') === 0) ? $logoPath : $siteUrl . '/' . ltrim($logoPath, '/');

    return [
        'name'     => getSetting('site_name', 'Deutsche Bank Holdings Delaware'),
        'email'    => getSetting('support_email', 'support@dbhacu.com'),
        'phone'    => getSetting('contact_phone', '+1 (800) 555-0199'),
        'logo'     => $logoPath,
        'logoUrl'  => $logoUrl,
        'siteUrl'  => $siteUrl,
    ];
}

/**
 * Send a professional banking email.
 *
 * @param string $to           Recipient email address
 * @param string $subject      Email subject line
 * @param string $customerName Customer's full name
 * @param string $title        Main heading inside the email body
 * @param string $message      HTML body content (the main paragraph / content area)
 * @param string $buttonText   Optional CTA button label (null = no button)
 * @param string $buttonLink   Optional CTA button URL (null = no button)
 * @param array  $details      Optional key→value pairs for a details table (e.g. ['Ref' => 'ABC123', 'Amount' => '$500'])
 * @param string $extra        Optional raw HTML inserted after the details table
 * @return bool                True if mail was accepted for delivery
 * @throws InvalidArgumentException if recipient is invalid
 */
function sendBankEmail(
    string $to,
    string $subject,
    string $customerName,
    string $title,
    string $message,
    ?string $buttonText = null,
    ?string $buttonLink = null,
    array  $details = [],
    string $extra = ''
): bool {
    // Validate
    if (!_email_valid($to)) {
        throw new InvalidArgumentException('Invalid recipient: ' . $to);
    }

    $bank  = _bank_defaults();
    $from  = $bank['email'];
    $name  = $bank['name'];

    // Sanitise all header values
    $to      = _email_sanitise($to);
    $subject = _email_sanitise($subject);

    // Build HTML from template
    $bankName      = $bank['name'];
    $supportEmail  = $bank['email'];
    $supportPhone  = $bank['phone'];
    $logoUrl       = $bank['logoUrl'];
    $siteUrl       = $bank['siteUrl'];

    ob_start();
    include __DIR__ . '/../templates/email_template.php';
    $htmlBody = ob_get_clean();

    // Headers
    $headers  = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=UTF-8\r\n";
    $headers .= "From: " . $name . " <" . $from . ">\r\n";
    $headers .= "Reply-To: " . $from . "\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";

    // Send
    $sent = mail($to, $subject, $htmlBody, $headers);

    if (!$sent) {
        error_log("[BankEmail] Failed to send to {$to}: {$subject}");
    }

    return $sent;
}

/**
 * Shorthand: send a simple notification email without button/details.
 */
function sendBankNotification(
    string $to,
    string $subject,
    string $customerName,
    string $title,
    string $message
): bool {
    return sendBankEmail($to, $subject, $customerName, $title, $message);
}

/**
 * Send a transfer confirmation email.
 * Reads transaction + transfer data from DB and builds a rich summary.
 * Safe to call from any transfer completion point.
 */
function sendTransferConfirmationEmail($db, string $userEmail, string $transId): void {
    // Guard: skip if already sent
    $check = mysqli_query($db, "SELECT email_sent FROM transactions WHERE trans_id = '" . mysqli_real_escape_string($db, $transId) . "'");
    if ($check && $row = mysqli_fetch_assoc($check)) {
        if ((int)$row['email_sent'] === 1) return;
    } else { return; }

    // Fetch user
    $u = mysqli_query($db, "SELECT firstname, lastname, usercurrency, checking_balance FROM users WHERE email = '" . mysqli_real_escape_string($db, $userEmail) . "'");
    if (!$u || mysqli_num_rows($u) === 0) return;
    $user = mysqli_fetch_assoc($u);
    $fullName = $user['firstname'] . ' ' . $user['lastname'];
    $currency  = $user['usercurrency'] ?? '$';

    // Fetch transaction
    $t = mysqli_query($db, "SELECT * FROM transactions WHERE trans_id = '" . mysqli_real_escape_string($db, $transId) . "'");
    if (!$t || mysqli_num_rows($t) === 0) return;
    $txn = mysqli_fetch_assoc($t);

    // Fetch transfer details (recipient)
    $x = mysqli_query($db, "SELECT * FROM transfers WHERE transfer_ref = '" . mysqli_real_escape_string($db, $transId) . "'");
    $recipient = '—';
    $method    = 'Inter-Bank Transfer';
    if ($x && mysqli_num_rows($x) > 0) {
        $xf = mysqli_fetch_assoc($x);
        $recipient = ($xf['accountholder'] ?? '') . ' / ' . ($xf['bankname'] ?? '');
    } else {
        // Check intra-bank
        $intra = mysqli_query($db, "SELECT t.*, u.firstname, u.lastname, u.account_num FROM transactions t JOIN users u ON t.user = u.account_num WHERE t.trans_id = '" . mysqli_real_escape_string($db, $transId) . "' AND t.type = 'Credit'");
        if ($intra && mysqli_num_rows($intra) > 0) {
            $ir = mysqli_fetch_assoc($intra);
            $recipient = $ir['firstname'] . ' ' . $ir['lastname'] . ' (' . $ir['account_num'] . ')';
            $method    = 'Intra-Bank Transfer';
        }
    }

    // Mask account number
    $maskedRecipient = preg_replace('/^(.+)(\d{4})$/', '•••• $2', $recipient);

    // Remaining balance
    $account = $txn['account'] ?? 'checking_balance';
    $remaining = $user[$account] ?? '0.00';

    $details = [
        'Reference'      => $transId,
        'Amount'         => formatCurrency((float)$txn['amount'], $currency),
        'Transfer Method' => $method,
        'Recipient'      => $maskedRecipient,
        'Date & Time'    => $txn['date'] ?? '—',
        'Status'         => 'Successful',
        'Remaining Balance' => formatCurrency((float)$remaining, $currency),
    ];
    if (!empty($txn['description'])) {
        $details['Description'] = $txn['description'];
    }

    try {
        $bank = _bank_defaults();
        $siteUrl = $bank['siteUrl'];
        $sent = sendBankEmail($userEmail, 'Transfer Confirmation — Ref: ' . $transId, $fullName,
            'Transfer Successfully Processed',
            '<p>Your transfer has been <strong style="color:#28a745;">successfully processed</strong>. Below are the transaction details:</p>',
            'View Dashboard', $siteUrl . '/dashboard/dashboard',
            $details
        );
        if ($sent) {
            mysqli_query($db, "UPDATE transactions SET email_sent = 1 WHERE trans_id = '" . mysqli_real_escape_string($db, $transId) . "'");
        }
    } catch (Exception $e) {
        error_log("[TransferEmail] Failed for {$transId}: " . $e->getMessage());
    }
}
