<?php
// send_custom_email.php
session_start();
require_once 'php/adminconfig.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer-master/src/Exception.php';
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: email_admin.php');
    exit;
}

// Process form data
$email_title = $_POST['email_title'] ?: 'Tradewave TT';
$email_type = $_POST['email_type'] === 'custom' ? $_POST['custom_email_type'] : $_POST['email_type'];
$message_body = $_POST['message_body'];
$recipients = $_POST['recipients'] ?? [];
$price_amount = $_POST['price_amount'] ?? null;
$price_currency = $_POST['price_currency'] ?? null;
$price_style = $_POST['price_style'] ?? null;
$include_know_more = isset($_POST['include_know_more']) ? 1 : 0;
$include_tradewave = isset($_POST['include_tradewave']) ? 1 : 0;
$table_data = $_POST['table_data'] ?? null;

// Handle file uploads
$uploaded_logos = [];
$attachment_file = null;
$upload_dir = 'uploads/';

// Ensure upload directory exists
if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0755, true);
}

// Process logo uploads
if (isset($_FILES['logos']) && !empty($_FILES['logos']['name'][0])) {
    for ($i = 0; $i < min(count($_FILES['logos']['name']), 3); $i++) {
        if ($_FILES['logos']['error'][$i] === UPLOAD_ERR_OK) {
            $temp_name = $_FILES['logos']['tmp_name'][$i];
            $original_name = $_FILES['logos']['name'][$i];
            $extension = pathinfo($original_name, PATHINFO_EXTENSION);
            $new_name = 'logo_' . time() . '_' . $i . '.' . $extension;
            $target_path = $upload_dir . $new_name;
            
            if (move_uploaded_file($temp_name, $target_path)) {
                $uploaded_logos[] = $new_name;
            }
        }
    }
}

// Process attachment upload
if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
    $temp_name = $_FILES['attachment']['tmp_name'];
    $original_name = $_FILES['attachment']['name'];
    $extension = pathinfo($original_name, PATHINFO_EXTENSION);
    $new_name = 'attachment_' . time() . '.' . $extension;
    $target_path = $upload_dir . $new_name;
    
    if (move_uploaded_file($temp_name, $target_path)) {
        $attachment_file = $new_name;
    }
}

// Validate recipients
if (empty($recipients)) {
    die('Error: No recipients selected.');
}

// Get recipient details
$placeholders = str_repeat('?,', count($recipients) - 1) . '?';
$stmt = $conn->prepare("SELECT id, firstname, lastname, email, currency_symbol FROM users WHERE id IN ($placeholders)");
$stmt->execute($recipients);
$user_details = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($user_details)) {
    die('Error: No valid recipients found.');
}

// Initialize email sending results
$success_count = 0;
$failed_emails = [];

// Send emails to each recipient
foreach ($user_details as $user) {
    $success = tw_send_custom_email(
        $user,
        $email_title,
        $email_type,
        $message_body,
        $price_amount,
        $price_currency,
        $price_style,
        $uploaded_logos,
        $attachment_file,
        $table_data,
        $include_know_more,
        $include_tradewave
    );
    
    if ($success) {
        $success_count++;
    } else {
        $failed_emails[] = [
            'user_id' => $user['id'],
            'email' => $user['email'],
            'name' => $user['firstname'] . ' ' . $user['lastname']
        ];
    }
}

// Save to email_logs table
try {
    $stmt = $conn->prepare("
        INSERT INTO email_logs (
            user_ids, email_type, custom_title, logo_1, logo_2, logo_3, 
            subject, message_body, price_amount, price_currency, price_style, 
            attachment_file, table_data, include_know_more_btn, include_tradewave_btn,
            success_count, failed_emails, admin_id
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    
    $stmt->execute([
        json_encode($recipients),
        $email_type,
        $email_title,
        $uploaded_logos[0] ?? null,
        $uploaded_logos[1] ?? null,
        $uploaded_logos[2] ?? null,
        $email_type,
        $message_body,
        $price_amount,
        $price_currency,
        $price_style,
        $attachment_file,
        $table_data,
        $include_know_more,
        $include_tradewave,
        $success_count,
        json_encode($failed_emails),
        $_SESSION['admin_id'] ?? 1
    ]);
    
    $log_id = $conn->lastInsertId();
    
} catch (PDOException $e) {
    error_log("Email log save error: " . $e->getMessage());
}

// Display results
echo "<!DOCTYPE html>
<html>
<head>
    <title>Email Sending Results</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; background: #f5f5f5; }
        .tw_result_container { background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .tw_success { color: #28a745; }
        .tw_error { color: #dc3545; }
        .tw_btn_back { background: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block; margin-top: 20px; }
    </style>
</head>
<body>
    <div class='tw_result_container'>
        <h2>Email Sending Results</h2>
        <div class='tw_success'>
            <strong>Successfully sent: {$success_count} emails</strong>
        </div>";

if (!empty($failed_emails)) {
    echo "<div class='tw_error'>
            <strong>Failed to send: " . count($failed_emails) . " emails</strong>
            <ul>";
    foreach ($failed_emails as $failed) {
        echo "<li>{$failed['name']} ({$failed['email']})</li>";
    }
    echo "</ul></div>";
}

echo "<a href='mailing.php' class='tw_btn_back'>Send Another Email</a>
    </div>
</body>
</html>";

function tw_send_custom_email($user, $title, $subject, $message, $amount, $currency, $price_style, $logos, $attachment, $table_data, $know_more_btn, $tradewave_btn) {
    try {
        $mail = new PHPMailer(true);
        
        // SMTP Configuration
        $mail->isSMTP();
        $mail->SMTPDebug = 0;
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = "tls";
        $mail->Port = 587;
        $mail->Host = "mail.tradewavett.xyz";
        $mail->Username = "official@tradewavett.xyz";
        $mail->Password = "#Trader00#";
        
        // Email settings
        $mail->isHTML(true);
        $mail->addAddress($user['email'], $user['firstname'] . ' ' . $user['lastname']);
        $mail->setFrom("official@tradewavett.xyz", $title);
        $mail->Subject = $subject;
        
        // Add attachment if exists
        if ($attachment) {
            $mail->addAttachment('uploads/' . $attachment);
        }
        
        // Generate email content
        $mail->Body = tw_generate_email_template($user, $title, $subject, $message, $amount, $currency, $price_style, $logos, $table_data, $know_more_btn, $tradewave_btn);
        
        return $mail->send();
        
    } catch (Exception $e) {
        error_log("Email sending error: " . $e->getMessage());
        return false;
    }
}

function tw_generate_email_template($user, $title, $subject, $message, $amount, $currency, $price_style, $logos, $table_data, $know_more_btn, $tradewave_btn) {
    $user_name = $user['firstname'];
    $user_currency = $user['currency_symbol'] ?: '$';
    
    // Generate logo section
    $logo_section = '';
    if (!empty($logos)) {
        $logo_section = '<div style="text-align: center; margin: 20px 0; background-color: #f4f4f4;">';
        foreach (array_slice($logos, 0, 3) as $logo) {
            $logo_url = 'https://administraor1998.tradewavett.xyz/uploads/' . $logo;
            $logo_section .= '<img src="' . $logo_url . '" style="width: 50px; height: 50px; border-radius: 50%; margin: 0 10px; border: 2px solid #e0e0e0;" alt="Brand Logo">';
        }
        $logo_section .= '</div>';
    }
    
    // Generate price section
    $price_section = '';
    if ($amount && $currency) {
        $price_colors = [
            'pending' => ['border' => '#ff9800', 'color' => '#ff9800', 'bg' => '#fff3e0'],
            'success' => ['border' => '#4caf50', 'color' => '#4caf50', 'bg' => '#e8f5e9'],
            'overdue' => ['border' => '#f44336', 'color' => '#f44336', 'bg' => '#ffebee']
        ];
        
        $style_colors = $price_colors[$price_style] ?? $price_colors['pending'];
        $currency_symbol = $currency === 'USD' ? '$' : 
                          ($currency === 'EUR' ? '€' : 
                          ($currency === 'GBP' ? '£' : 
                          ($currency === 'TTD' ? 'TTD$' : $user_currency)));
        
        $price_section = '<div style="text-align: center;">
            <div style="display: inline-block; padding: 15px 30px; width: 90%; 
                        color: ' . $style_colors['color'] . '; background-color: ' . $style_colors['bg'] . '; 
                        border-radius: 3px; font-size: 20px; font-weight: bold;">
                ' . $currency_symbol . number_format($amount, 2) . '
            </div>
        </div>';
    }
    
    // Generate table section
    $table_section = '';
    if ($table_data && $table_data !== 'null') {
        $table_info = json_decode($table_data, true);
        if ($table_info && !empty($table_info['headers'])) {
            $table_section = '<div style="margin: 30px 0;">
                <table style="width: 100%; border-collapse: collapse; font-size: 14px;">
                    <thead>
                        <tr style="background-color: #f8f9fa;">';
            
            foreach ($table_info['headers'] as $header) {
                $table_section .= '<th style="padding: 12px; border: 1px solid #dee2e6; font-weight: bold; text-align: left;">' . htmlspecialchars($header) . '</th>';
            }
            
            $table_section .= '</tr></thead><tbody>';
            
            if (!empty($table_info['rows'])) {
                foreach ($table_info['rows'] as $row) {
                    $table_section .= '<tr>';
                    foreach ($row as $cell) {
                        $table_section .= '<td style="padding: 10px; border: 1px solid #dee2e6;">' . htmlspecialchars($cell) . '</td>';
                    }
                    $table_section .= '</tr>';
                }
            }
            
            $table_section .= '</tbody></table></div>';
        }
    }
    
    // Generate button sections
    $button_section = '';
    if ($know_more_btn || $tradewave_btn) {
        $button_section = '<div style="text-align: center; margin: 30px 0;">';
        
        if ($tradewave_btn) {
            $button_section .= '<a href="https://tradewavett.xyz" style="display: inline-block; padding: 12px 25px; 
                                background: #000; color: white; 
                                text-decoration: none; border-radius: 6px; font-weight: bold; margin: 0 10px;">
                                know more
                               </a>';
        }
        
        $button_section .= '</div>';
    }
    
    $html_template = '
    <!DOCTYPE html>
    <html lang="en">
    <style>
    .email_footer_vwx { 
                background: #f8f9fa; 
                padding: 25px 20px; 
                border-radius: 0 0 14px 14px;
                border-top: 1px solid #dee2e6; 
                text-align: center;
            }
            .footer_text_yza { 
                font-size: 12px; 
                color: #6c757d; 
                line-height: 1.5; 
                margin: 5px 0;
            }
            .social_icons_bcd { 
                margin: 15px 0; 
                text-align: center;
            }
            .social_icon_efg { 
                display: inline-block; 
                width: 32px; 
                height: 32px; 
                margin: 0 8px; 
                background: #007bff; 
                border-radius: 50%; 
                line-height: 32px; 
                color: white; 
                text-decoration: none; 
                font-size: 14px;
            }
            .tracking_info_hij { 
                background: #f4f4f4; 
                padding: 15px; 
                margin: 10px 0; 
                border-left: 4px solid gray;
            }
    </style>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>' . htmlspecialchars($title) . '</title>
    </head>
    <body style="font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Arial, sans-serif; 
                 line-height: 1.2; color: #333; background-color: #f4f6f8; margin: 0; padding: 0;">
        
        <div style="max-width: 600px; margin: 0 auto; background-color: white; border-radius: 10px; border: 1px solid #bdbdbd; overflow: hidden;">
            
            <!-- Custom Logo Section -->
            ' . $logo_section . '
            
            <!-- Header Section -->
            <div style="background: linear-gradient(135deg, #b71c1c 0%, #fff 100%); 
                        height: 3px; border-bottom: 1px solid #bdbdbd;">
            </div>
            
            <!-- Message Body -->
            <div style="padding: 20px;">
                <p style="font-size: 14px; color: #2c3e50; margin-bottom: 10px; font-weight: bold;">
                    Dear ' . htmlspecialchars($user_name) . ',
                </p>
                
                <div style="font-size: 13px; color: #34495e; line-height: 1.4; margin-bottom: 15px;">
                    ' . nl2br(htmlspecialchars($message)) . '
                </div>
                
                ' . $price_section . '
                ' . $table_section . '
                ' . $button_section . '
            </div>
            
            <!-- Footer Section -->
            <div class="email_footer_vwx">
                
                
                <div class="footer_text_yza">
                    This is a notic from Trinidad and Tobago Exchange Commisiion (TTSEC).
                </div>
                <div class="footer_text_yza">
                    This email was sent from an automated system. Please do not reply directly.
                </div>
                <div class="footer_text_yza">
                    <strong>Contact Us:</strong> official@tradewavett.xyz | www.ttsec.com | www.Tradewavett.xyz| +1 (832) 892‑4309 [whatsapp]
                </div>
                <div class="footer_text_yza">
                    © 2025 TradewaveTT Company. All rights reserved.
                </div>
            </div>
        </div>
    </body>
    </html>';
    
    return $html_template;
}
?>