<?php
/**
 * notify_lib.php
 * All the specific notification "shapes" (registration OTP, login OTP,
 * login alert, subscription expiry reminder) built on top of
 * smtp_mailer.php + email_template.php.
 */
// Server defaults to UTC, which showed login-alert times ~5.5 hours behind
// actual IST time. Every date() call in this file should read Indian time.
date_default_timezone_set('Asia/Kolkata');

require_once __DIR__ . '/smtp_mailer.php';
require_once __DIR__ . '/email_template.php';
require_once __DIR__ . '/whatsapp_lib.php';

/**
 * Fire-and-forget WhatsApp send - failures here never block the email
 * flow (email is always the guaranteed channel; WhatsApp is best-effort).
 */
function notify_try_whatsapp($conn, $phone, $message) {
    if (empty($phone)) return;
    if (!wa_gateway_configured($conn)) return;
    send_whatsapp_message($conn, $phone, $message);
}

function generate_otp_code() {
    return str_pad((string)random_int(0, 999999), 6, '0', STR_PAD_LEFT);
}

function get_brand_name($conn) {
    $res = mysqli_query($conn, "SELECT brand_name FROM site_settings LIMIT 1");
    $row = $res ? mysqli_fetch_assoc($res) : null;
    return $row['brand_name'] ?? 'NeoPay';
}

/**
 * Stores a fresh OTP on the user row and emails it.
 * $purpose: 'register' | 'login'
 */
function issue_email_otp($conn, $userId, $email, $name, $purpose) {
    $otp = generate_otp_code();
    $expiresAt = date('Y-m-d H:i:s', strtotime('+10 minutes'));

    $stmt = $conn->prepare("UPDATE users SET otp_code = ?, otp_expires_at = ?, otp_purpose = ? WHERE id = ?");
    if (!$stmt) return ['ok' => false, 'message' => 'Setup incomplete - run sql/RUN_THIS_ALL_IN_ONE.sql first.'];
    $stmt->bind_param("sssi", $otp, $expiresAt, $purpose, $userId);
    $stmt->execute();
    $stmt->close();

    $brand = get_brand_name($conn);
    $headlineMap = [
        'register' => 'Verify Your Email Address',
        'login' => 'Your Login Verification Code',
        'reset' => 'Reset Your Password',
    ];
    $headline = $headlineMap[$purpose] ?? 'Your Verification Code';
    $introMap = [
        'register' => "Apna account activate karne ke liye neeche diya gaya code enter karein:",
        'login' => "Login complete karne ke liye neeche diya gaya code enter karein:",
        'reset' => "Apna password reset karne ke liye neeche diya gaya code enter karein:",
    ];
    $intro = "Namaste <b>" . htmlspecialchars($name) . "</b>,<br>" . ($introMap[$purpose] ?? $introMap['login']);

    $body = "<p>{$intro}</p>" . render_otp_block($otp) . "<p style='color:#8a8a9c;font-size:13px'>Yeh code 10 minute me expire ho jayega. Agar aapne yeh request nahi ki, is email ko ignore kar dein.</p>";

    $html = render_email_template($brand, $headline, $body);
    $sent = send_smtp_email($conn, $email, $name, "{$otp} - Your {$brand} Verification Code", $html);

    $phoneQueryRes = mysqli_query($conn, "SELECT COALESCE(whatsapp_number, mobile) AS phone FROM users WHERE id = " . (int)$userId);
    $phoneRow = $phoneQueryRes ? mysqli_fetch_assoc($phoneQueryRes) : null;
    $waLabelMap = ['register' => 'verification', 'reset' => 'password reset', 'login' => 'login'];
    $waLabel = $waLabelMap[$purpose] ?? 'login';
    $waMessage = "Aapka {$brand} {$waLabel} code hai: *{$otp}*\n\n10 minute me expire ho jayega.";
    notify_try_whatsapp($conn, $phoneRow['phone'] ?? null, $waMessage);

    return ['ok' => $sent, 'message' => $sent ? 'OTP sent' : smtp_last_error()];
}

/**
 * Verifies a submitted OTP against what's stored. On success, clears the
 * OTP fields (and for 'register' purpose, marks the email verified) so it
 * can't be reused.
 */
function verify_email_otp($conn, $userId, $submittedOtp, $purpose) {
    $stmt = $conn->prepare("SELECT otp_code, otp_expires_at, otp_purpose FROM users WHERE id = ?");
    if (!$stmt) return ['ok' => false, 'message' => 'Setup incomplete - run sql/RUN_THIS_ALL_IN_ONE.sql first.'];
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if (!$row || empty($row['otp_code'])) {
        return ['ok' => false, 'message' => 'No pending OTP. Please request a new one.'];
    }
    if ($row['otp_purpose'] !== $purpose) {
        return ['ok' => false, 'message' => 'This code was issued for a different action.'];
    }
    if (strtotime($row['otp_expires_at']) < time()) {
        return ['ok' => false, 'message' => 'This code has expired. Please request a new one.'];
    }
    if (!hash_equals((string)$row['otp_code'], trim((string)$submittedOtp))) {
        return ['ok' => false, 'message' => 'Incorrect code. Please try again.'];
    }

    $extra = ($purpose === 'register') ? ", email_verified = 'Yes'" : "";
    $conn->query("UPDATE users SET otp_code = NULL, otp_expires_at = NULL, otp_purpose = NULL{$extra} WHERE id = " . (int)$userId);

    return ['ok' => true, 'message' => 'Verified'];
}

/**
 * "New login detected" security notice - sent after a successful login,
 * informational only (doesn't block anything).
 */
function send_login_alert($conn, $userId, $email, $name) {
    $brand = get_brand_name($conn);
    $ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
    if (strpos($ip, ',') !== false) {
        // X-Forwarded-For can be a chain of proxy IPs - the first one is
        // the real client, the rest are intermediate hops.
        $ip = trim(explode(',', $ip)[0]);
    }
    $time = date('d M Y, h:i A');

    $body = "<p>Namaste <b>" . htmlspecialchars($name) . "</b>,</p>
        <p>Aapke account me abhi login hua hai:</p>
        <table style='width:100%;background:#f7f7fb;border-radius:10px;padding:4px;margin:14px 0'>
            <tr><td style='padding:10px 14px;color:#666'>IP Address</td><td style='padding:10px 14px;font-weight:700;color:#14141f'>" . htmlspecialchars($ip) . "</td></tr>
            <tr><td style='padding:10px 14px;color:#666'>Time</td><td style='padding:10px 14px;font-weight:700;color:#14141f'>" . htmlspecialchars($time) . "</td></tr>
        </table>
        <p>Agar yeh aap the, is email ko ignore kar dein.<br>Agar yeh aap nahi the, turant apna password badal dein.</p>";

    $html = render_email_template($brand, 'New Login to Your Account', $body);
    $sent = send_smtp_email($conn, $email, $name, "Security Alert: New login to your {$brand} account", $html);

    $phoneQueryRes = mysqli_query($conn, "SELECT COALESCE(whatsapp_number, mobile) AS phone FROM users WHERE id = " . (int)$userId);
    $phoneRow = $phoneQueryRes ? mysqli_fetch_assoc($phoneQueryRes) : null;
    $waMessage = "Dear *" . $name . "*,\n\nYour account was recently logged in from:\n- *IP Address:* {$ip}\n- *Time:* {$time}\n\nIf this was you, you can safely ignore this message.\nIf this was not you, please change your password immediately.\n\nVisit: https://" . ($_SERVER['SERVER_NAME'] ?? '') ;
    notify_try_whatsapp($conn, $phoneRow['phone'] ?? null, $waMessage);

    return $sent;
}

/**
 * Payment Received notification - sent to the MERCHANT (not the customer)
 * when one of their orders is confirmed paid.
 */
function send_payment_success_notification($conn, $userId, $orderId, $amount, $utr, $gateway) {
    $userQueryRes = mysqli_query($conn, "SELECT name, email, COALESCE(whatsapp_number, mobile) AS phone FROM users WHERE id = " . (int)$userId);
    $userRow = $userQueryRes ? mysqli_fetch_assoc($userQueryRes) : null;
    if (!$userRow) return false;

    $brand = get_brand_name($conn);
    $dateStr = date('d M Y, h:i A');
    $amountFmt = number_format((float)$amount, 2);

    $body = "<p style='color:#16A34A;font-weight:800;font-size:17px;margin:0 0 14px'>Payment Received!</p>
        <p>Hello <b>" . htmlspecialchars($userRow['name'] ?? 'there') . "</b>,</p>
        <p>You have received a new payment of ₹{$amountFmt}.</p>
        <table style='width:100%;background:#f7f7fb;border-radius:10px;padding:4px;margin:14px 0'>
            <tr><td style='padding:8px 14px;color:#666'>Order ID</td><td style='padding:8px 14px;font-weight:700;color:#14141f'>" . htmlspecialchars($orderId) . "</td></tr>
            <tr><td style='padding:8px 14px;color:#666'>Amount</td><td style='padding:8px 14px;font-weight:700;color:#16A34A'>₹{$amountFmt}</td></tr>
            <tr><td style='padding:8px 14px;color:#666'>UTR / Ref</td><td style='padding:8px 14px;font-weight:700;color:#14141f'>" . htmlspecialchars($utr ?: 'N/A') . "</td></tr>
            <tr><td style='padding:8px 14px;color:#666'>Gateway</td><td style='padding:8px 14px;font-weight:700;color:#14141f'>" . htmlspecialchars($gateway) . "</td></tr>
            <tr><td style='padding:8px 14px;color:#666'>Date</td><td style='padding:8px 14px;font-weight:700;color:#14141f'>{$dateStr}</td></tr>
        </table>";

    $html = render_email_template($brand, "Payment Received - ₹{$amountFmt}", $body);
    $sent = send_smtp_email($conn, $userRow['email'], $userRow['name'] ?? '', "Payment Received - ₹{$amountFmt} | Order #{$orderId}", $html);

    $waMessage = "✅ *Payment Received*\n\nAmount: ₹{$amountFmt}\nOrder ID: {$orderId}\nUTR: " . ($utr ?: 'N/A') . "\nGateway: {$gateway}\nDate: {$dateStr}";
    notify_try_whatsapp($conn, $userRow['phone'] ?? null, $waMessage);

    return $sent;
}

/**
 * Payment Failed notification - sent to the MERCHANT when an order times
 * out / fails, so they know a customer tried to pay and it didn't land.
 */
function send_payment_failed_notification($conn, $userId, $orderId, $amount, $gateway, $reason = 'Payment not received') {
    $userQueryRes = mysqli_query($conn, "SELECT name, email, COALESCE(whatsapp_number, mobile) AS phone FROM users WHERE id = " . (int)$userId);
    $userRow = $userQueryRes ? mysqli_fetch_assoc($userQueryRes) : null;
    if (!$userRow) return false;

    $brand = get_brand_name($conn);
    $dateStr = date('d M Y, h:i A');
    $amountFmt = number_format((float)$amount, 2);

    $body = "<p style='color:#D64545;font-weight:800;font-size:17px;margin:0 0 14px'>Payment Failed</p>
        <p>Hello <b>" . htmlspecialchars($userRow['name'] ?? 'there') . "</b>,</p>
        <p>A payment attempt on your account did not complete.</p>
        <table style='width:100%;background:#f7f7fb;border-radius:10px;padding:4px;margin:14px 0'>
            <tr><td style='padding:8px 14px;color:#666'>Order ID</td><td style='padding:8px 14px;font-weight:700;color:#14141f'>" . htmlspecialchars($orderId) . "</td></tr>
            <tr><td style='padding:8px 14px;color:#666'>Amount</td><td style='padding:8px 14px;font-weight:700;color:#D64545'>₹{$amountFmt}</td></tr>
            <tr><td style='padding:8px 14px;color:#666'>Reason</td><td style='padding:8px 14px;font-weight:700;color:#14141f'>" . htmlspecialchars($reason) . "</td></tr>
            <tr><td style='padding:8px 14px;color:#666'>Gateway</td><td style='padding:8px 14px;font-weight:700;color:#14141f'>" . htmlspecialchars($gateway) . "</td></tr>
            <tr><td style='padding:8px 14px;color:#666'>Date</td><td style='padding:8px 14px;font-weight:700;color:#14141f'>{$dateStr}</td></tr>
        </table>";

    $html = render_email_template($brand, "Payment Failed - ₹{$amountFmt}", $body);
    $sent = send_smtp_email($conn, $userRow['email'], $userRow['name'] ?? '', "Payment Failed | Order #{$orderId}", $html);

    $waMessage = "❌ *Payment Failed*\n\nAmount: ₹{$amountFmt}\nOrder ID: {$orderId}\nReason: {$reason}\nGateway: {$gateway}\nDate: {$dateStr}";
    notify_try_whatsapp($conn, $userRow['phone'] ?? null, $waMessage);

    return $sent;
}
function send_subscription_reminder($conn, $userId, $email, $name, $planName, $daysLeft, $expiryDate) {
    $brand = get_brand_name($conn);
    $urgency = $daysLeft <= 1 ? 'Aaj/Kal' : "{$daysLeft} din me";

    $body = "<p>Namaste <b>" . htmlspecialchars($name) . "</b>,</p>
        <p>Aapka plan <b>\"" . htmlspecialchars($planName) . "\"</b> <b>{$urgency}</b> expire ho raha hai (" . htmlspecialchars($expiryDate) . ").</p>
        <p>Expire hone ke baad naye merchant connect karna aur transactions lena band ho jayega. Time rehte renew kar lein taaki koi rukavat na ho.</p>";

    $html = render_email_template($brand, 'Your Subscription is Expiring Soon', $body, 'Renew Now', 'https://' . $_SERVER['SERVER_NAME'] . '/auth/subscription');
    $sent = send_smtp_email($conn, $email, $name, "Reminder: Your {$brand} plan expires in {$daysLeft} day(s)", $html);

    $phoneQueryRes = mysqli_query($conn, "SELECT COALESCE(whatsapp_number, mobile) AS phone FROM users WHERE id = " . (int)$userId);
    $phoneRow = $phoneQueryRes ? mysqli_fetch_assoc($phoneQueryRes) : null;
    $waMessage = "Dear *{$name}*,\n\nAapka *{$brand}* plan \"{$planName}\" *{$daysLeft} din* me expire ho raha hai ({$expiryDate}).\n\nTime rehte renew kar lein: https://" . ($_SERVER['SERVER_NAME'] ?? '') . "/auth/subscription";
    notify_try_whatsapp($conn, $phoneRow['phone'] ?? null, $waMessage);

    return $sent;
}
