<?php
// PHPMailer Configuration
// This file contains all email configuration settings

// ===== IMPORTANT: PHPMailer Installation =====
// 1. Download PHPMailer from: https://github.com/PHPMailer/PHPMailer
// 2. Extract and place in: backend/phpmailer/ directory
// 3. Or install via Composer: composer require phpmailer/phpmailer
// 4. Update MAIL_USERNAME and MAIL_PASSWORD below with your Gmail/email credentials
// =============================================

// Email Configuration
define('MAIL_HOST', 'smtp.gmail.com');
define('MAIL_PORT', 587);
define('MAIL_USERNAME', 'mak.6052413@gmail.com'); // Replace with your Gmail
define('MAIL_PASSWORD', 'ddarcmevqmutoiru'); // Replace with your App Password
define('MAIL_FROM_EMAIL', 'mak.6052413@gmail.com');
define('MAIL_FROM_NAME', 'Restaurant Booking');

// TEST MODE: Set to true to log OTPs to file instead of sending emails
define('TEST_MODE', false);
define('OTP_LOG_FILE', __DIR__ . '/../assets/uploads/otp_test_log.txt');

// OTP Settings
define('OTP_LENGTH', 6);
define('OTP_EXPIRY_MINUTES', 15);
define('OTP_MAX_ATTEMPTS', 5);

// Password Reset Settings
define('PASSWORD_RESET_EXPIRY_MINUTES', 30);
define('PASSWORD_RESET_MAX_ATTEMPTS', 5);

// Helper function to send email using PHPMailer
function sendEmailWithOTP($recipientEmail, $otp, $purpose = 'signup') {
    if ($purpose === 'reset') {
        $purpose = 'password_reset';
    }

    // In TEST_MODE, log to file instead of sending
    if (TEST_MODE) {
        $logContent = date('Y-m-d H:i:s') . " - Email: {$recipientEmail}, OTP: {$otp}, Purpose: {$purpose}\n";
        @file_put_contents(OTP_LOG_FILE, $logContent, FILE_APPEND);
        return ['success' => true, 'message' => 'Email sent successfully'];
    }

    // Production mode: Send via SMTP
    // Load PHPMailer
    require_once __DIR__ . '/phpmailer/src/Exception.php';
    require_once __DIR__ . '/phpmailer/src/PHPMailer.php';
    require_once __DIR__ . '/phpmailer/src/SMTP.php';

    $mail = new PHPMailer\PHPMailer\PHPMailer(true);

    try {
        // For development/testing: Check if we can connect to local sendmail first
        // Server settings
        $mail->isSMTP();
        $mail->Host = MAIL_HOST;
        $mail->SMTPAuth = true;
        $mail->Username = MAIL_USERNAME;
        $mail->Password = MAIL_PASSWORD;
        $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = MAIL_PORT;
        $mail->SMTPDebug = 0;
        $mail->Debugoutput = 'error_log';
        
        // Allow self-signed certificates (for local testing)
        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );

        // Recipients
        $mail->setFrom(MAIL_FROM_EMAIL, MAIL_FROM_NAME);
        $mail->addAddress($recipientEmail);

        // Content based on purpose
        if ($purpose === 'signup') {
            $mail->isHTML(true);
            $mail->Subject = 'Email Verification - Granny Restaurant';
            $mail->Body = getSignupEmailTemplate($otp, $recipientEmail);
            $mail->AltBody = "Your OTP for email verification is: {$otp}. This OTP will expire in 15 minutes.";
        } elseif ($purpose === 'password_reset') {
            $mail->isHTML(true);
            $mail->Subject = 'Password Reset - Granny Restaurant';
            $mail->Body = getPasswordResetEmailTemplate($otp, $recipientEmail);
            $mail->AltBody = "Your OTP for password reset is: {$otp}. This OTP will expire in 30 minutes.";
        } else {
            // Safe fallback to avoid PHPMailer "Message body empty" errors.
            $mail->isHTML(false);
            $mail->Subject = 'OTP - Granny Restaurant';
            $mail->Body = "Your OTP is: {$otp}";
            $mail->AltBody = "Your OTP is: {$otp}";
        }

        $mail->send();
        return ['success' => true, 'message' => 'Email sent successfully'];
    } catch (PHPMailer\PHPMailer\Exception $e) {
        error_log("PHPMailer Error: " . $e->getMessage());
        return ['success' => false, 'message' => 'Failed to send email: ' . $e->getMessage()];
    } catch (Exception $e) {
        error_log("General Exception: " . $e->getMessage());
        return ['success' => false, 'message' => 'Failed to send email: ' . $e->getMessage()];
    }
}

// Send email using PHPMailer (SMTP)
function sendEmailWithPHPMailer($recipientEmail, $otp, $purpose = 'signup') {
    if ($purpose === 'reset') {
        $purpose = 'password_reset';
    }

    $mail = new PHPMailer\PHPMailer\PHPMailer(true);

    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host = MAIL_HOST;
        $mail->SMTPAuth = true;
        $mail->Username = MAIL_USERNAME;
        $mail->Password = MAIL_PASSWORD;
        $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = MAIL_PORT;

        // Recipients
        $mail->setFrom(MAIL_FROM_EMAIL, MAIL_FROM_NAME);
        $mail->addAddress($recipientEmail);

        // Content based on purpose
        if ($purpose === 'signup') {
            $mail->isHTML(true);
            $mail->Subject = 'Email Verification - Granny Restaurant';
            $mail->Body = getSignupEmailTemplate($otp, $recipientEmail);
            $mail->AltBody = "Your OTP for email verification is: {$otp}. This OTP will expire in 15 minutes.";
        } elseif ($purpose === 'password_reset') {
            $mail->isHTML(true);
            $mail->Subject = 'Password Reset - Granny Restaurant';
            $mail->Body = getPasswordResetEmailTemplate($otp, $recipientEmail);
            $mail->AltBody = "Your OTP for password reset is: {$otp}. This OTP will expire in 30 minutes.";
        } else {
            $mail->isHTML(false);
            $mail->Subject = 'OTP - Granny Restaurant';
            $mail->Body = "Your OTP is: {$otp}";
            $mail->AltBody = "Your OTP is: {$otp}";
        }

        $mail->send();
        return ['success' => true, 'message' => 'Email sent successfully'];
    } catch (PHPMailer\PHPMailer\Exception $e) {
        return ['success' => false, 'message' => 'Failed to send email: ' . $e->getMessage()];
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Failed to send email: ' . $e->getMessage()];
    }
}

// Email template for signup verification
function getSignupEmailTemplate($otp, $email) {
    return "
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body {
                    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                    background-color: #f5f5f5;
                    margin: 0;
                    padding: 0;
                }
                .container {
                    max-width: 600px;
                    margin: 20px auto;
                    background-color: #ffffff;
                    border-radius: 8px;
                    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                    overflow: hidden;
                }
                .header {
                    background: linear-gradient(135deg, #8B4513 0%, #A0522D 100%);
                    color: #ffffff;
                    padding: 30px;
                    text-align: center;
                }
                .header h1 {
                    margin: 0;
                    font-size: 28px;
                    font-weight: bold;
                }
                .content {
                    padding: 30px;
                }
                .otp-box {
                    background-color: #f8f9fa;
                    border: 2px dashed #8B4513;
                    border-radius: 6px;
                    padding: 20px;
                    text-align: center;
                    margin: 20px 0;
                }
                .otp-code {
                    font-size: 32px;
                    font-weight: bold;
                    color: #8B4513;
                    letter-spacing: 5px;
                    font-family: 'Courier New', monospace;
                }
                .footer {
                    background-color: #f8f9fa;
                    padding: 20px;
                    text-align: center;
                    font-size: 12px;
                    color: #666;
                    border-top: 1px solid #eee;
                }
                .warning {
                    color: #d9534f;
                    font-size: 13px;
                    margin-top: 10px;
                }
            </style>
        </head>
        <body>
            <div class=\"container\">
                <div class=\"header\">
                    <h1>🍽️ Granny Restaurant</h1>
                </div>
                <div class=\"content\">
                    <p>Hello,</p>
                    <p>Thank you for creating an account with Granny Restaurant! We're excited to have you join us.</p>
                    <p>To verify your email address and complete your registration, please use the following One-Time Password (OTP):</p>
                    <div class=\"otp-box\">
                        <div class=\"otp-code\">{$otp}</div>
                    </div>
                    <p><strong>Important Information:</strong></p>
                    <ul>
                        <li>This OTP is valid for <strong>15 minutes only</strong></li>
                        <li>Each OTP can be used <strong>only once</strong></li>
                        <li>Do not share this code with anyone</li>
                    </ul>
                    <p>If you did not create this account, please ignore this email.</p>
                </div>
                <div class=\"footer\">
                    <p>&copy; " . MAIL_FROM_NAME . ". All rights reserved.</p>
                    <p class=\"warning\">This is an automated message. Please do not reply to this email.</p>
                </div>
            </div>
        </body>
        </html>
    ";
}

// Email template for password reset
function getPasswordResetEmailTemplate($otp, $email) {
    return "
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body {
                    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                    background-color: #f5f5f5;
                    margin: 0;
                    padding: 0;
                }
                .container {
                    max-width: 600px;
                    margin: 20px auto;
                    background-color: #ffffff;
                    border-radius: 8px;
                    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                    overflow: hidden;
                }
                .header {
                    background: linear-gradient(135deg, #8B4513 0%, #A0522D 100%);
                    color: #ffffff;
                    padding: 30px;
                    text-align: center;
                }
                .header h1 {
                    margin: 0;
                    font-size: 28px;
                    font-weight: bold;
                }
                .content {
                    padding: 30px;
                }
                .otp-box {
                    background-color: #f8f9fa;
                    border: 2px dashed #8B4513;
                    border-radius: 6px;
                    padding: 20px;
                    text-align: center;
                    margin: 20px 0;
                }
                .otp-code {
                    font-size: 32px;
                    font-weight: bold;
                    color: #8B4513;
                    letter-spacing: 5px;
                    font-family: 'Courier New', monospace;
                }
                .footer {
                    background-color: #f8f9fa;
                    padding: 20px;
                    text-align: center;
                    font-size: 12px;
                    color: #666;
                    border-top: 1px solid #eee;
                }
                .warning {
                    color: #d9534f;
                    font-size: 13px;
                    margin-top: 10px;
                }
            </style>
        </head>
        <body>
            <div class=\"container\">
                <div class=\"header\">
                    <h1>🍽️ Granny Restaurant</h1>
                </div>
                <div class=\"content\">
                    <p>Hello,</p>
                    <p>We received a request to reset the password for your Granny Restaurant account.</p>
                    <p>To reset your password, please use the following One-Time Password (OTP):</p>
                    <div class=\"otp-box\">
                        <div class=\"otp-code\">{$otp}</div>
                    </div>
                    <p><strong>Important Information:</strong></p>
                    <ul>
                        <li>This OTP is valid for <strong>30 minutes only</strong></li>
                        <li>Each OTP can be used <strong>only once</strong></li>
                        <li>Do not share this code with anyone</li>
                    </ul>
                    <p>If you did not request a password reset, please ignore this email and your account remains secure.</p>
                </div>
                <div class=\"footer\">
                    <p>&copy; " . MAIL_FROM_NAME . ". All rights reserved.</p>
                    <p class=\"warning\">This is an automated message. Please do not reply to this email.</p>
                </div>
            </div>
        </body>
        </html>
    ";
}

// Generate OTP
function generateOTP($length = OTP_LENGTH) {
    $digits = '0123456789';
    $otp = '';
    for ($i = 0; $i < $length; $i++) {
        $otp .= $digits[random_int(0, 9)];
    }
    return $otp;
}

?>
