<?php

class MailService {
    
    /**
     * Send a password reset email.
     * 
     * @param string $email The recipient's email address
     * @param string $token The reset token
     * @return bool Returns true if the email was "sent" (or logged)
     */
    public static function sendPasswordReset(string $email, string $token): bool {
        // Construct the reset link based on the environment
        $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
        $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
        
        // Dynamically determine the application root to support both local and live servers
        $scriptDir = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/\\');
        $appRoot   = rtrim(dirname($scriptDir), '/\\');
        $appRoot   = ($appRoot === DIRECTORY_SEPARATOR) ? '' : $appRoot;
        
        $resetLink = "$protocol://$host$appRoot/user/forgot-password.php?token=$token&step=2";
        
        $subject = "Reset Your Password - ShopNest";
        $message = self::getResetEmailTemplate($resetLink);
        
        // Headers for HTML email
        $headers  = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
        $headers .= "From: ShopNest <noreply@shopnest.com>" . "\r\n";
        
        // 1. Log the email for local development (MUST HAVE for XAMPP)
        self::logEmail($email, $subject, $message, $resetLink);
        
        // 2. Attempt real mail sending
        // On many local setups, this will fail or do nothing, which is why we log it above.
        try {
            return @mail($email, $subject, $message, $headers);
        } catch (Exception $e) {
            return false;
        }
    }
    
    /**
     * Professional HTML Email Template for Password Reset
     */
    private static function getResetEmailTemplate(string $link): string {
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                .email-container { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; max-width: 600px; margin: 0 auto; border: 1px solid #eee; border-radius: 10px; overflow: hidden; }
                .header { background: #ff6b35; padding: 30px; text-align: center; color: white; }
                .content { padding: 40px; color: #333; line-height: 1.6; }
                .button { display: inline-block; padding: 15px 30px; background: #ff6b35; color: white; text-decoration: none; border-radius: 25px; font-weight: bold; margin-top: 20px; }
                .footer { background: #f8f9fa; padding: 20px; text-align: center; font-size: 12px; color: #777; }
                .link-alt { word-break: break-all; color: #ff6b35; font-size: 11px; margin-top: 20px; }
            </style>
        </head>
        <body>
            <div class='email-container'>
                <div class='header'>
                    <h1 style='margin:0;'>ShopNest</h1>
                </div>
                <div class='content'>
                    <h2>Password Reset Request</h2>
                    <p>Hello,</p>
                    <p>We received a request to reset the password for your ShopNest account. Click the button below to set a new password:</p>
                    <div style='text-align: center;'>
                        <a href='$link' class='button'>Reset Password</a>
                    </div>
                    <p>This link will expire in 1 hour. If you didn't request this, you can safely ignore this email.</p>
                    <hr style='border:0; border-top:1px solid #eee; margin: 30px 0;'>
                    <p>If the button doesn't work, copy and paste this link into your browser:</p>
                    <div class='link-alt'>$link</div>
                </div>
                <div class='footer'>
                    &copy; " . date('Y') . " ShopNest E-commerce. All rights reserved.
                </div>
            </div>
        </body>
        </html>
        ";
    }
    
    /**
     * Log email to a local file for development visibility.
     */
    private static function logEmail(string $to, string $subject, string $message, string $link): void {
        $logDir = __DIR__ . '/../storage/logs';
        if (!is_dir($logDir)) {
            mkdir($logDir, 0777, true);
        }
        
        $logFile = $logDir . '/mail.log';
        $timestamp = date('Y-m-d H:i:s');
        $logEntry = "[$timestamp] TO: $to | SUBJECT: $subject\r\n";
        $logEntry .= "RESET LINK: $link\r\n";
        $logEntry .= "--------------------------------------------------\r\n\r\n";
        
        file_put_contents($logFile, $logEntry, FILE_APPEND);
    }
}
