<?php
/**
 * Estreka Ratsaklubi - Email konfiguratsioon (PARANDATUD)
 * SMTP seadistused ja meilide saatmine - toimib mitmerealiste vastustega
 */

// Email konfiguratsioon
define('SMTP_HOST', 'mail.flamicroz.com');              // Hostingu SMTP server
define('SMTP_PORT', 465);                               // SSL port
define('SMTP_USERNAME', 'estreka@flamicroz.com');       // Täielik email aadress
define('SMTP_PASSWORD', '6!vOtDL1DZDp');                // Email parool
define('SMTP_SECURE', 'ssl');                           // SSL ühendus

// Email aadressid
define('FROM_EMAIL', 'estreka@flamicroz.com');
define('FROM_NAME', 'Estreka Ratsaklubi');
define('ADMIN_EMAIL', 'tiinalass@gmail.com');
define('ADMIN_NAME', 'Estreka Admin');

define('EMAIL_ENABLED', true);  
define('USE_SMTP', false);      // ⚡ Kasuta PHP mail() funktsiooni

/**
 * ⚡ PARANDATUD: Saadab emaili (SMTP või PHP mail() funktsiooniga)
 */
function sendEmail($to_email, $to_name, $subject, $html_body, $text_body = '') {
    if (!EMAIL_ENABLED) {
        error_log("Email sending disabled - would send to: $to_email");
        return true; // Test režiimis tagasta "õnnestumine"
    }
    
    // Genereeri text versioon kui pole antud
    if (empty($text_body)) {
        $text_body = strip_tags($html_body);
        $text_body = html_entity_decode($text_body, ENT_QUOTES, 'UTF-8');
    }
    
    // ⚡ PARANDUS: Kontrolli USE_SMTP seadistust
    if (defined('USE_SMTP') && USE_SMTP) {
        // Kasuta SMTP
        $headers = [];
        $headers[] = "MIME-Version: 1.0";
        $headers[] = "Content-Type: text/html; charset=UTF-8";
        $headers[] = "From: " . FROM_NAME . " <" . FROM_EMAIL . ">";
        $headers[] = "Reply-To: " . ADMIN_EMAIL;
        $headers[] = "X-Mailer: PHP/" . phpversion();
        
        return sendSMTPEmailFixed($to_email, $subject, $html_body, implode("\r\n", $headers));
    } else {
        // ⚡ KASUTA PHP MAIL() FUNKTSIOONI
        $headers = [];
        $headers[] = "MIME-Version: 1.0";
        $headers[] = "Content-Type: text/html; charset=UTF-8";
        $headers[] = "From: " . FROM_NAME . " <" . FROM_EMAIL . ">";
        $headers[] = "Reply-To: " . ADMIN_EMAIL;
        $headers[] = "X-Mailer: PHP/" . phpversion();
        
        $header_string = implode("\r\n", $headers);
        
        return mail($to_email, $subject, $html_body, $header_string);
    }
}

/**
 * PARANDATUD SMTP email saatmine - oskab lugeda mitmerealisi vastuseid
 */
function sendSMTPEmailFixed($to, $subject, $body, $headers) {
    try {
        // Kasuta timeout'i
        $context = stream_context_create([
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            ]
        ]);
        
        $smtp = stream_socket_client(
            (SMTP_SECURE === 'ssl' ? 'ssl://' : '') . SMTP_HOST . ':' . SMTP_PORT,
            $errno,
            $errstr,
            10, // 10 sekundi timeout
            STREAM_CLIENT_CONNECT,
            $context
        );
        
        if (!$smtp) {
            throw new Exception("SMTP ühendus ebaõnnestus: $errstr ($errno)");
        }
        
        // Loe server tervitus (võib olla mitu rida)
        $greeting = readSMTPResponseFixed($smtp);
        if (!$greeting['success'] || $greeting['code'] !== '220') {
            throw new Exception("Server not ready: " . $greeting['message']);
        }
        
        // EHLO käsk
        fputs($smtp, "EHLO " . ($_SERVER['HTTP_HOST'] ?? 'localhost') . "\r\n");
        $ehlo_response = readSMTPResponseFixed($smtp);
        
        if (!$ehlo_response['success'] || !in_array($ehlo_response['code'], ['250', '220'])) {
            throw new Exception("EHLO failed: " . $ehlo_response['message']);
        }
        
        // Kui server ei ole SSL ja toetab STARTTLS
        if (SMTP_SECURE === 'tls' && strpos($ehlo_response['full_message'], 'STARTTLS') !== false) {
            fputs($smtp, "STARTTLS\r\n");
            $starttls_response = readSMTPResponseFixed($smtp);
            
            if ($starttls_response['success'] && $starttls_response['code'] === '220') {
                // Käivita TLS
                if (stream_socket_enable_crypto($smtp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
                    // Tee uus EHLO pärast TLS
                    fputs($smtp, "EHLO " . ($_SERVER['HTTP_HOST'] ?? 'localhost') . "\r\n");
                    $ehlo_response = readSMTPResponseFixed($smtp);
                } else {
                    throw new Exception("TLS aktiveerimine ebaõnnestus");
                }
            }
        }
        
        // Kontrolli kas server toetab AUTH LOGIN
        if (strpos($ehlo_response['full_message'], 'AUTH') === false) {
            throw new Exception("Server ei toeta autentimist");
        }
        
        // AUTH LOGIN
        fputs($smtp, "AUTH LOGIN\r\n");
        $auth_response = readSMTPResponseFixed($smtp);
        if (!$auth_response['success'] || $auth_response['code'] !== '334') {
            throw new Exception("AUTH LOGIN failed: " . $auth_response['message']);
        }
        
        // Kasutajanimi
        fputs($smtp, base64_encode(SMTP_USERNAME) . "\r\n");
        $user_response = readSMTPResponseFixed($smtp);
        if (!$user_response['success'] || $user_response['code'] !== '334') {
            throw new Exception("Username auth failed: " . $user_response['message']);
        }
        
        // Parool
        fputs($smtp, base64_encode(SMTP_PASSWORD) . "\r\n");
        $pass_response = readSMTPResponseFixed($smtp);
        if (!$pass_response['success'] || $pass_response['code'] !== '235') {
            throw new Exception("Password auth failed: " . $pass_response['message']);
        }
        
        // MAIL FROM
        fputs($smtp, "MAIL FROM: <" . FROM_EMAIL . ">\r\n");
        $mail_response = readSMTPResponseFixed($smtp);
        if (!$mail_response['success'] || $mail_response['code'] !== '250') {
            throw new Exception("MAIL FROM failed: " . $mail_response['message']);
        }
        
        // RCPT TO
        fputs($smtp, "RCPT TO: <$to>\r\n");
        $rcpt_response = readSMTPResponseFixed($smtp);
        if (!$rcpt_response['success'] || $rcpt_response['code'] !== '250') {
            throw new Exception("RCPT TO failed: " . $rcpt_response['message']);
        }
        
        // DATA
        fputs($smtp, "DATA\r\n");
        $data_response = readSMTPResponseFixed($smtp);
        if (!$data_response['success'] || $data_response['code'] !== '354') {
            throw new Exception("DATA command failed: " . $data_response['message']);
        }
        
        // Email sisu
        fputs($smtp, "To: $to\r\n");
        fputs($smtp, "Subject: $subject\r\n");
        fputs($smtp, $headers . "\r\n\r\n");
        fputs($smtp, $body . "\r\n.\r\n");
        
        $send_response = readSMTPResponseFixed($smtp);
        if (!$send_response['success'] || $send_response['code'] !== '250') {
            throw new Exception("Email sending failed: " . $send_response['message']);
        }
        
        // QUIT
        fputs($smtp, "QUIT\r\n");
        fclose($smtp);
        
        return true;
        
    } catch (Exception $e) {
        error_log("SMTP Error: " . $e->getMessage());
        if (isset($smtp) && $smtp) {
            fclose($smtp);
        }
        return false;
    }
}

/**
 * Loe SMTP vastus (võib olla mitu rida) - PARANDATUD
 */
function readSMTPResponseFixed($smtp) {
    $response = [
        'success' => false,
        'code' => '',
        'message' => '',
        'full_message' => ''
    ];
    
    $full_response = '';
    
    while (true) {
        $line = fgets($smtp, 515);
        if ($line === false) {
            break;
        }
        
        $full_response .= $line;
        
        // Kontrolli kas see on viimane rida (kood ilma miinusmärgita)
        if (preg_match('/^(\d{3})\s/', $line, $matches)) {
            $response['code'] = $matches[1];
            $response['success'] = true;
            break;
        } elseif (preg_match('/^(\d{3})-/', $line, $matches)) {
            $response['code'] = $matches[1];
            // Jätka lugemist, kuna see on mitmerealisev vastus
            continue;
        }
    }
    
    $response['message'] = trim($full_response);
    $response['full_message'] = $full_response;
    
    return $response;
}

/**
 * Genereeri kinnituskoodi
 */
function generateVerificationToken() {
    return bin2hex(random_bytes(32));
}

/**
 * Genereeri parooli taastamise token
 */
function generateResetToken() {
    return bin2hex(random_bytes(40));
}

/**
 * Registreerimise kinnitusmail (PARANDATUD)
 */
function sendRegistrationEmail($email, $name, $token) {
    $subject = "Kinnita oma Estreka Ratsaklubi konto";
    $verification_url = emailUrl("verify-email.php?token=" . urlencode($token));
    
    $html_body = getEmailTemplate('registration', [
        'name' => $name,
        'verification_url' => $verification_url,
        'site_url' => emailUrl()
    ]);
    
    return sendEmail($email, $name, $subject, $html_body);
}

/**
 * Parooli taastamise mail (PARANDATUD)
 */
function sendPasswordResetEmail($email, $name, $token) {
    $subject = "Parooli taastamine - Estreka Ratsaklubi";
    $reset_url = emailUrl("reset-password.php?token=" . urlencode($token));
    
    $html_body = getEmailTemplate('password_reset', [
        'name' => $name,
        'reset_url' => $reset_url,
        'site_url' => emailUrl()
    ]);
    
    return sendEmail($email, $name, $subject, $html_body);
}

/**
 * Email template'id (PARANDATUD)
 */
function getEmailTemplate($type, $vars = []) {
    $base_template = '
    <!DOCTYPE html>
    <html lang="et">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>{{title}}</title>
        <style>
            body { font-family: Arial, sans-serif; margin: 0; padding: 0; background-color: #f8fafc; }
            .container { max-width: 600px; margin: 0 auto; background: white; }
            .header { background: linear-gradient(135deg, #2563eb, #1d4ed8); color: white; padding: 40px 30px; text-align: center; }
            .header h1 { margin: 0; font-size: 28px; }
            .content { padding: 40px 30px; }
            .content h2 { color: #1f2937; margin-bottom: 20px; }
            .content p { color: #4b5563; line-height: 1.6; margin-bottom: 15px; }
            .button { display: inline-block; background: #2563eb; color: white; padding: 15px 30px; text-decoration: none; border-radius: 5px; margin: 20px 0; font-weight: bold; }
            .button:hover { background: #1d4ed8; }
            .footer { background: #f3f4f6; padding: 20px 30px; text-align: center; color: #6b7280; font-size: 14px; }
            .footer a { color: #2563eb; text-decoration: none; }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>🐴 Estreka Ratsaklubi</h1>
            </div>
            <div class="content">
                {{content}}
            </div>
            <div class="footer">
                <p>See e-mail saadeti automaatselt. Palun ära vasta sellele meilile.</p>
                <p><a href="{{site_url}}">Külasta meie kodulehte</a> | <a href="mailto:' . ADMIN_EMAIL . '">Võta ühendust</a></p>
            </div>
        </div>
    </body>
    </html>';
    
    $templates = [
        'registration' => [
            'title' => 'Kinnita oma konto',
            'content' => '
                <h2>Tere, {{name}}!</h2>
                <p>Aitäh registreerumise eest Estreka Ratsaklubi süsteemis!</p>
                <p>Oma konto aktiveerimiseks kliki allolevale nupule:</p>
                <a href="{{verification_url}}" class="button">Kinnita konto</a>
                <p>Kui nupp ei tööta, kopeeri järgnev link oma brauseri aadressiribale:</p>
                <p style="word-break: break-all; color: #2563eb;">{{verification_url}}</p>
                <p><strong>Oluline:</strong> See link kehtib 24 tundi.</p>
                <p>Kui sa ei registreerunud meie süsteemis, võid selle e-maili ignoreerida.</p>
            '
        ],
        'password_reset' => [
            'title' => 'Parooli taastamine',
            'content' => '
                <h2>Tere, {{name}}!</h2>
                <p>Sa küsisid parooli taastamist Estreka Ratsaklubi kontole.</p>
                <p>Uue parooli loomiseks kliki allolevale nupule:</p>
                <a href="{{reset_url}}" class="button">Taasta parool</a>
                <p>Kui nupp ei tööta, kopeeri järgnev link oma brauseri aadressiribale:</p>
                <p style="word-break: break-all; color: #2563eb;">{{reset_url}}</p>
                <p><strong>Oluline:</strong> See link kehtib 1 tund.</p>
                <p>Kui sa ei küsinud parooli taastamist, võid selle e-maili ignoreerida.</p>
            '
        ]
    ];
    
    if (!isset($templates[$type])) {
        return '';
    }
    
    $template = $templates[$type];
    $html = str_replace('{{title}}', $template['title'], $base_template);
    $html = str_replace('{{content}}', $template['content'], $html);
    
    // Asenda muutujad
    foreach ($vars as $key => $value) {
        $html = str_replace('{{' . $key . '}}', htmlspecialchars($value), $html);
    }
    
    return $html;
}

/**
 * Test email funktsioon (PARANDATUD)
 */
function testEmail($to_email = null) {
    if (!$to_email) {
        $to_email = ADMIN_EMAIL;
    }
    
    $subject = "Test email - Estreka Ratsaklubi";
    $html_body = '
        <h2>Test email õnnestus!</h2>
        <p>Kui sa näed seda sõnumit, siis e-mail süsteem toimib.</p>
        <p><strong>Aeg:</strong> ' . date('d.m.Y H:i:s') . '</p>
        <p><strong>Server:</strong> ' . $_SERVER['HTTP_HOST'] . '</p>
        <p><strong>Saatja:</strong> ' . FROM_EMAIL . '</p>
        <p><strong>Meetod:</strong> ' . (USE_SMTP ? 'SMTP' : 'PHP mail()') . '</p>
    ';
    
    return sendEmail($to_email, 'Test', $subject, $html_body);
}
?>