<?php
/**
 * OTP Verification Helper Functions
 * Shared across signup.php, auth.php, and verify_otp.php
 */

/**
 * Generate a cryptographically secure 6-digit OTP
 */
function generateOtp() {
    return random_int(100000, 999999);
}

/**
 * Store hashed OTP in database with expiry
 */
function storeOtp($conn, $clientId, $otp, $expiryMinutes = 10) {
    $hashedOtp = password_hash((string)$otp, PASSWORD_DEFAULT);
    $expiry = date("Y-m-d H:i:s", strtotime("+{$expiryMinutes} minutes"));
    
    $stmt = $conn->prepare("UPDATE clients SET 
        otp_code = :otp_code, 
        otp_expiry = :otp_expiry, 
        otp_attempts = 0, 
        otp_status = 'pending',
        email_verified = 0
        WHERE client_id = :client_id");
    
    return $stmt->execute([
        "otp_code"   => $hashedOtp,
        "otp_expiry" => $expiry,
        "client_id"  => $clientId
    ]);
}

/**
 * Verify OTP code against stored hash
 */
function verifyOtpCode($storedHash, $inputOtp) {
    return password_verify((string)$inputOtp, $storedHash);
}

/**
 * Mask email address for display (e.g., s****j@gmail.com)
 */
function maskEmail($email) {
    $parts = explode("@", $email);
    if (count($parts) !== 2) return $email;
    
    $name = $parts[0];
    $domain = $parts[1];
    
    if (strlen($name) <= 2) {
        $masked = $name[0] . str_repeat("*", max(1, strlen($name) - 1));
    } else {
        $masked = $name[0] . str_repeat("*", strlen($name) - 2) . $name[strlen($name) - 1];
    }
    
    return $masked . "@" . $domain;
}

/**
 * Send OTP email with branded HTML template
 */
function sendOtpEmail($to, $otp, $siteName, $smtpFrom, $expiryMinutes = 10) {
    $otpString = str_split((string)$otp);
    $otpDigits = '';
    foreach ($otpString as $digit) {
        $otpDigits .= "<span style='display:inline-block;width:45px;height:50px;line-height:50px;text-align:center;font-size:28px;font-weight:bold;background:#f0f4ff;border:2px solid #4361ee;border-radius:8px;margin:0 4px;color:#4361ee;font-family:monospace;'>{$digit}</span>";
    }
    
    $htmlContent = "
    <html>
    <head>
        <meta charset='UTF-8'>
        <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    </head>
    <body style='margin:0;padding:0;background-color:#f4f6f9;font-family:Arial,Helvetica,sans-serif;'>
        <table width='100%' cellpadding='0' cellspacing='0' style='background-color:#f4f6f9;padding:40px 0;'>
            <tr>
                <td align='center'>
                    <table width='500' cellpadding='0' cellspacing='0' style='background-color:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 20px rgba(0,0,0,0.08);'>
                        <!-- Header -->
                        <tr>
                            <td style='background:linear-gradient(135deg,#4361ee 0%,#3a0ca3 100%);padding:30px 40px;text-align:center;'>
                                <h1 style='color:#ffffff;margin:0;font-size:22px;font-weight:700;letter-spacing:0.5px;'>" . htmlspecialchars($siteName) . "</h1>
                                <p style='color:rgba(255,255,255,0.85);margin:8px 0 0;font-size:14px;'>Email Verification</p>
                            </td>
                        </tr>
                        <!-- Body -->
                        <tr>
                            <td style='padding:40px;'>
                                <p style='color:#333;font-size:16px;margin:0 0 20px;line-height:1.6;'>Hello,</p>
                                <p style='color:#555;font-size:15px;margin:0 0 25px;line-height:1.6;'>Please use the following verification code to complete your registration. This code will expire in <strong>{$expiryMinutes} minutes</strong>.</p>
                                
                                <!-- OTP Code -->
                                <div style='text-align:center;margin:30px 0;padding:25px;background:#fafbff;border-radius:10px;border:1px dashed #d0d5f5;'>
                                    <p style='color:#888;font-size:12px;text-transform:uppercase;letter-spacing:2px;margin:0 0 15px;'>Your Verification Code</p>
                                    {$otpDigits}
                                </div>
                                
                                <!-- Warning -->
                                <div style='background:#fff8e1;border-left:4px solid #ffc107;padding:12px 16px;border-radius:4px;margin:25px 0;'>
                                    <p style='color:#856404;font-size:13px;margin:0;line-height:1.5;'>
                                        <strong>⚠️ Security Warning:</strong> Never share this code with anyone. Our team will never ask for your verification code.
                                    </p>
                                </div>
                                
                                <p style='color:#888;font-size:13px;margin:20px 0 0;line-height:1.5;'>If you did not create an account, please ignore this email.</p>
                            </td>
                        </tr>
                        <!-- Footer -->
                        <tr>
                            <td style='background:#f8f9fa;padding:20px 40px;text-align:center;border-top:1px solid #eee;'>
                                <p style='color:#aaa;font-size:12px;margin:0;'>This is an automated message from " . htmlspecialchars($siteName) . ". Please do not reply.</p>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </body>
    </html>";

    $subject = "Your Verification Code - " . $siteName;
    $headers  = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=UTF-8\r\n";
    $headers .= "From: " . $siteName . " <" . $smtpFrom . ">\r\n";

    return mail($to, $subject, $htmlContent, $headers);
}

/**
 * Check if resend cooldown has passed
 */
function canResendOtp($cooldownTimestamp, $cooldownSeconds = 60) {
    if (!$cooldownTimestamp) return true;
    return (time() - $cooldownTimestamp) >= $cooldownSeconds;
}

/**
 * Check if resend limit per hour is reached
 */
function checkResendLimit($conn, $clientId, $maxPerHour = 3) {
    $client = $conn->prepare("SELECT otp_resend_count, otp_resend_reset_at FROM clients WHERE client_id = :id");
    $client->execute(["id" => $clientId]);
    $row = $client->fetch(PDO::FETCH_ASSOC);
    
    if (!$row) return false;
    
    // Reset counter if more than 1 hour has passed
    if ($row["otp_resend_reset_at"] && strtotime($row["otp_resend_reset_at"]) < time()) {
        $reset = $conn->prepare("UPDATE clients SET otp_resend_count = 0, otp_resend_reset_at = NULL WHERE client_id = :id");
        $reset->execute(["id" => $clientId]);
        return true; // Can resend
    }
    
    return $row["otp_resend_count"] < $maxPerHour;
}

/**
 * Increment resend counter
 */
function incrementResendCount($conn, $clientId) {
    $client = $conn->prepare("SELECT otp_resend_count, otp_resend_reset_at FROM clients WHERE client_id = :id");
    $client->execute(["id" => $clientId]);
    $row = $client->fetch(PDO::FETCH_ASSOC);
    
    $newCount = ($row["otp_resend_count"] ?? 0) + 1;
    $resetAt = $row["otp_resend_reset_at"];
    
    // Set reset time if this is the first resend in the window
    if (!$resetAt || strtotime($resetAt) < time()) {
        $resetAt = date("Y-m-d H:i:s", strtotime("+1 hour"));
    }
    
    $update = $conn->prepare("UPDATE clients SET otp_resend_count = :count, otp_resend_reset_at = :reset_at WHERE client_id = :id");
    $update->execute([
        "count"    => $newCount,
        "reset_at" => $resetAt,
        "id"       => $clientId
    ]);
}
