<?php
/**
 * Authentication Helper Functions
 * Real-Time OTP Generation & Email Sending using PHPMailer
 */

require_once __DIR__ . '/PHPMailer/src/PHPMailer.php';
require_once __DIR__ . '/PHPMailer/src/SMTP.php';
require_once __DIR__ . '/PHPMailer/src/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

/**
 * Generate a random 6-digit OTP
 */
function generateOTP() {
    return str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
}

/**
 * Send OTP via Email using PHPMailer
 * 
 * @param string $email - Customer email address
 * @param string $otp - Generated OTP code
 * @param string $name - Customer name (optional)
 * @return array - ['success' => bool, 'message' => string]
 */
function sendOTPEmail($email, $otp, $name = 'Customer') {
    try {
        $mail = new PHPMailer(true);
        
        // Server settings
        $mail->SMTPDebug = 0;
        $mail->isSMTP();
        $mail->Host       = 'mail.zemaraimgroups.com'; // Change to your SMTP server
        $mail->SMTPAuth   = true;
        // Update these credentials with your email service
        $mail->Username   = 'info.zemaraimgroups.com'; // Change to your email
        $mail->Password   = 'zemaraimgroups@123';    // Change to your app password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;

        // Recipients
        $mail->setFrom('noreply@nexthm.com', 'NextHM Real Estate');
        $mail->addAddress($email, $name);

        // Email content
        $mail->isHTML(true);
        $mail->Subject = 'Password Reset OTP - NextHM Real Estate';
        
        // Create beautiful HTML email template
        $htmlBody = <<<HTML
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <style>
                * { margin: 0; padding: 0; box-sizing: border-box; }
                body { font-family: 'Poppins', sans-serif; background-color: #f8f9fa; padding: 20px; }
                .container { max-width: 500px; margin: 0 auto; }
                .email-wrapper { background: white; border-radius: 10px; box-shadow: 0 5px 20px rgba(0,0,0,0.1); overflow: hidden; }
                .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 40px 20px; text-align: center; color: white; }
                .header h1 { font-size: 28px; margin-bottom: 10px; }
                .header p { font-size: 14px; opacity: 0.9; }
                .content { padding: 40px 30px; }
                .greeting { font-size: 16px; color: #1a1a1a; margin-bottom: 20px; }
                .greeting strong { color: #667eea; }
                .description { font-size: 14px; color: #666; line-height: 1.6; margin-bottom: 30px; }
                .otp-section { background: #f8f9fa; border-left: 4px solid #667eea; padding: 20px; border-radius: 5px; margin-bottom: 30px; }
                .otp-label { font-size: 12px; color: #999; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 10px; }
                .otp-code { font-size: 32px; font-weight: 700; color: #667eea; letter-spacing: 5px; text-align: center; font-family: 'Courier New', monospace; }
                .expiry { font-size: 12px; color: #ff6b6b; text-align: center; margin-top: 15px; }
                .footer-text { font-size: 13px; color: #999; line-height: 1.8; margin-bottom: 20px; }
                .footer-text a { color: #667eea; text-decoration: none; }
                .footer-text a:hover { text-decoration: underline; }
                .warning { background: rgba(255, 107, 107, 0.1); border: 1px solid rgba(255, 107, 107, 0.2); padding: 15px; border-radius: 5px; margin-bottom: 20px; font-size: 12px; color: #ff6b6b; }
                .action-button { display: inline-block; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px 30px; border-radius: 5px; text-decoration: none; font-weight: 600; margin-bottom: 20px; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="email-wrapper">
                    <div class="header">
                        <h1>🔐 Password Reset</h1>
                        <p>NextHM Real Estate Platform</p>
                    </div>
                    
                    <div class="content">
                        <div class="greeting">
                            Hello <strong>{$name}</strong>,
                        </div>
                        
                        <div class="description">
                            We received a request to reset your NextHM account password. 
                            Use the verification code below to proceed with your password reset.
                        </div>
                        
                        <div class="otp-section">
                            <div class="otp-label">Your Verification Code</div>
                            <div class="otp-code">{$otp}</div>
                            <div class="expiry">⏱️ This code expires in 15 minutes</div>
                        </div>
                        
                        <div class="warning">
                            <strong>⚠️ Security Notice:</strong> Never share this code with anyone. 
                            NextHM staff will never ask for this code via email, phone, or message.
                        </div>
                        
                        <div class="footer-text">
                            <strong>If you didn't request this reset:</strong><br>
                            You can safely ignore this email. Your account remains secure, and no changes will be made without your authorization.
                        </div>
                        
                        <div class="footer-text">
                            <strong>Need help?</strong><br>
                            Contact our support team at <a href="mailto:support@nexthm.com">support@nexthm.com</a> or visit 
                            <a href="https://nexthm.com/support">nexthm.com/support</a>
                        </div>
                    </div>
                </div>
            </div>
        </body>
        </html>
        HTML;

        $mail->Body = $htmlBody;
        $mail->AltBody = "Your OTP is: {$otp}. This code expires in 15 minutes.";

        if ($mail->send()) {
            return [
                'success' => true,
                'message' => 'OTP sent successfully to your email'
            ];
        }
    } catch (Exception $e) {
        error_log("PHPMailer Error: " . $mail->ErrorInfo);
        return [
            'success' => false,
            'message' => 'Unable to send OTP. Please try again later.'
        ];
    } catch (\Exception $e) {
        error_log("General Error: " . $e->getMessage());
        return [
            'success' => false,
            'message' => 'An error occurred. Please try again later.'
        ];
    }
}

/**
 * Store OTP in database
 * 
 * @param mysqli $conn - Database connection
 * @param string $email - User email
 * @param string $otp - Generated OTP
 * @return array - ['success' => bool, 'message' => string]
 */
function storeOTP($conn, $email, $otp) {
    try {
        // Delete old OTPs for this email
        $deleteQuery = "DELETE FROM password_resets WHERE email = ? AND is_used = FALSE";
        $stmt = $conn->prepare($deleteQuery);
        
        if (!$stmt) {
            return [
                'success' => false,
                'message' => 'Database error'
            ];
        }
        
        $stmt->bind_param('s', $email);
        $stmt->execute();
        $stmt->close();

        // Insert new OTP with 15-minute expiry
        $insertQuery = "INSERT INTO password_resets (email, otp, created_at, expires_at) 
                       VALUES (?, ?, NOW(), DATE_ADD(NOW(), INTERVAL 15 MINUTE))";
        $stmt = $conn->prepare($insertQuery);
        
        if (!$stmt) {
            return [
                'success' => false,
                'message' => 'Database error'
            ];
        }
        
        $stmt->bind_param('ss', $email, $otp);
        
        if ($stmt->execute()) {
            $stmt->close();
            return [
                'success' => true,
                'message' => 'OTP stored successfully'
            ];
        } else {
            $stmt->close();
            return [
                'success' => false,
                'message' => 'Failed to store OTP'
            ];
        }
    } catch (\Exception $e) {
        error_log("Error storing OTP: " . $e->getMessage());
        return [
            'success' => false,
            'message' => 'An error occurred'
        ];
    }
}

/**
 * Verify OTP
 * 
 * @param mysqli $conn - Database connection
 * @param string $email - User email
 * @param string $otp - OTP to verify
 * @return array - ['success' => bool, 'message' => string, 'otp_id' => int|null]
 */
function verifyOTP($conn, $email, $otp) {
    try {
        // Check if OTP exists, is not used, and is not expired
        $query = "SELECT id FROM password_resets 
                 WHERE email = ? AND otp = ? AND is_used = FALSE 
                 AND expires_at > NOW() 
                 LIMIT 1";
        
        $stmt = $conn->prepare($query);
        
        if (!$stmt) {
            return [
                'success' => false,
                'message' => 'Verification failed'
            ];
        }
        
        $stmt->bind_param('ss', $email, $otp);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 0) {
            $stmt->close();
            return [
                'success' => false,
                'message' => 'Invalid or expired OTP'
            ];
        }

        $row = $result->fetch_assoc();
        $otp_id = $row['id'];
        $stmt->close();

        // Mark OTP as verified
        $updateQuery = "UPDATE password_resets SET verified_at = NOW() WHERE id = ?";
        $updateStmt = $conn->prepare($updateQuery);
        $updateStmt->bind_param('i', $otp_id);
        $updateStmt->execute();
        $updateStmt->close();

        return [
            'success' => true,
            'message' => 'OTP verified successfully',
            'otp_id' => $otp_id
        ];
    } catch (\Exception $e) {
        error_log("Error verifying OTP: " . $e->getMessage());
        return [
            'success' => false,
            'message' => 'Verification error'
        ];
    }
}

/**
 * Mark OTP as used
 * 
 * @param mysqli $conn - Database connection
 * @param int $otp_id - OTP record ID
 * @return bool
 */
function markOTPAsUsed($conn, $otp_id) {
    try {
        $query = "UPDATE password_resets SET is_used = TRUE WHERE id = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param('i', $otp_id);
        $result = $stmt->execute();
        $stmt->close();
        
        return $result;
    } catch (\Exception $e) {
        error_log("Error marking OTP as used: " . $e->getMessage());
        return false;
    }
}

/**
 * Get user by email
 * 
 * @param mysqli $conn - Database connection
 * @param string $email - User email
 * @return array|null - User data or null if not found
 */
function getUserByEmail($conn, $email) {
    try {
        $query = "SELECT id, firstname, lastname, email FROM customers WHERE email = ? LIMIT 1";
        $stmt = $conn->prepare($query);
        
        if (!$stmt) {
            return null;
        }
        
        $stmt->bind_param('s', $email);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 0) {
            $stmt->close();
            return null;
        }

        $user = $result->fetch_assoc();
        $stmt->close();
        
        return $user;
    } catch (\Exception $e) {
        error_log("Error getting user: " . $e->getMessage());
        return null;
    }
}

/**
 * Reset password for user
 * 
 * @param mysqli $conn - Database connection
 * @param string $email - User email
 * @param string $newPassword - New password
 * @return array - ['success' => bool, 'message' => string]
 */
function resetPassword($conn, $email, $newPassword) {
    try {
        $hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT);
        
        $query = "UPDATE customers SET password = ? WHERE email = ?";
        $stmt = $conn->prepare($query);
        
        if (!$stmt) {
            return [
                'success' => false,
                'message' => 'Database error'
            ];
        }
        
        $stmt->bind_param('ss', $hashedPassword, $email);
        
        if ($stmt->execute()) {
            $stmt->close();
            
            // Mark all OTPs for this email as used
            $markQuery = "UPDATE password_resets SET is_used = TRUE WHERE email = ?";
            $markStmt = $conn->prepare($markQuery);
            $markStmt->bind_param('s', $email);
            $markStmt->execute();
            $markStmt->close();
            
            return [
                'success' => true,
                'message' => 'Password reset successfully'
            ];
        } else {
            $stmt->close();
            return [
                'success' => false,
                'message' => 'Failed to reset password'
            ];
        }
    } catch (\Exception $e) {
        error_log("Error resetting password: " . $e->getMessage());
        return [
            'success' => false,
            'message' => 'An error occurred'
        ];
    }
}

/**
 * Validate password strength
 * 
 * @param string $password - Password to validate
 * @return array - ['valid' => bool, 'message' => string]
 */
function validatePassword($password) {
    if (strlen($password) < 8) {
        return [
            'valid' => false,
            'message' => 'Password must be at least 8 characters long'
        ];
    }
    
    if (!preg_match('/[A-Z]/', $password)) {
        return [
            'valid' => false,
            'message' => 'Password must contain at least one uppercase letter'
        ];
    }
    
    if (!preg_match('/[a-z]/', $password)) {
        return [
            'valid' => false,
            'message' => 'Password must contain at least one lowercase letter'
        ];
    }
    
    if (!preg_match('/[0-9]/', $password)) {
        return [
            'valid' => false,
            'message' => 'Password must contain at least one number'
        ];
    }
    
    return [
        'valid' => true,
        'message' => 'Password is valid'
    ];
}

?>
