<?php
session_start();

// Security check
if (!isset($_SESSION['admin_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

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';

// Email Template Function
function buildEmailTemplate($firstName, $bodyText, $amount, $currency, $primaryLogo, $secondaryLogo) {
    $secondaryLogoHtml = $secondaryLogo ? '<img src="' . htmlspecialchars($secondaryLogo) . '" alt="Logo" style="height: 40px; margin-left: 20px;">' : '';
    
    return '<!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <style>
            body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; }
            .email-wrapper { max-width: 650px; margin: 30px auto; background: #ffffff; border-radius: 10px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.1); }
            .email-header { background: linear-gradient(135deg, #8B4513 0%, #A0522D 100%); padding: 30px 20px; text-align: center; }
            .email-header img { height: 50px; vertical-align: middle; }
            .email-body { padding: 40px 30px; color: #333333; line-height: 1.8; }
            .greeting { font-size: 18px; font-weight: 600; color: #8B4513; margin-bottom: 20px; }
            .amount-box { background: #fff5f0; border-left: 4px solid #FF8C00; padding: 20px; margin: 25px 0; border-radius: 5px; }
            .amount-label { font-size: 14px; color: #666; margin-bottom: 5px; }
            .amount-value { font-size: 32px; font-weight: 600; color: #FF8C00; }
            .cta-button { display: inline-block; background: #8B4513; color: #ffffff; padding: 15px 40px; text-decoration: none; border-radius: 5px; margin: 25px 0; font-weight: 600; }
            .email-footer { background: #f9f9f9; padding: 30px; text-align: center; color: #666; font-size: 13px; border-top: 1px solid #e0e0e0; }
        </style>
    </head>
    <body>
        <div class="email-wrapper">
            <div class="email-header">
                <img src="' . htmlspecialchars($primaryLogo) . '" alt="TradewaveTT">' . $secondaryLogoHtml . '
            </div>
            <div class="email-body">
                <div class="greeting">Dear ' . htmlspecialchars($firstName) . ',</div>
                <p>' . nl2br(htmlspecialchars($bodyText)) . '</p>
                <div class="amount-box">
                    <div class="amount-label">Subscription Amount Due:</div>
                    <div class="amount-value">' . htmlspecialchars($currency) . ' ' . number_format($amount, 2) . '</div>
                </div>
                <p style="margin-top: 25px;">To ensure uninterrupted access to our premium features, please review the attached document for detailed payment instructions.</p>
                <center><a href="https://www.tradewavett.xyz" class="cta-button">Know More</a></center>
            </div>
            <div class="email-footer">
                <strong>TradewaveTT</strong><br>
                &copy; ' . date('Y') . ' TradewaveTT. All rights reserved.
            </div>
        </div>
    </body>
    </html>';
}

// Handle Email Sending
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_send_email'])) {
    header('Content-Type: application/json');
    
    try {
        $senderName = $_POST['sender_name'] ?? 'Tradewave TT';
        $subject = $_POST['email_subject'] ?? 'Subscription Repayment';
        $amount = $_POST['amount'] ?? '0.00';
        $currency = $_POST['currency'] ?? 'USD';
        $emailBody = $_POST['email_body'] ?? '';
        $recipients = isset($_POST['recipients']) ? json_decode($_POST['recipients'], true) : [];
        $uploadedPrimaryLogo = $_POST['primary_logo_path'] ?? 'https://tradewavett.xyz/images/icon.png';
        $uploadedSecondaryLogo = $_POST['secondary_logo_path'] ?? '';
        
        if (empty($recipients)) {
            echo json_encode(['success' => false, 'message' => 'Please select at least one recipient']);
            exit();
        }
        
        if (empty($emailBody)) {
            echo json_encode(['success' => false, 'message' => 'Email body cannot be empty']);
            exit();
        }
        
        $successCount = 0;
        $failCount = 0;
        $errorMessages = [];
        
        foreach ($recipients as $userId) {
            try {
                $stmt = $conn->prepare("SELECT firstname, lastname, email FROM users WHERE id = :id");
                $stmt->execute([':id' => $userId]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if (!$user || empty($user['email'])) {
                    $errorMessages[] = "Invalid user ID: $userId";
                    $failCount++;
                    continue;
                }
                
                $emailContent = buildEmailTemplate($user['firstname'], $emailBody, $amount, $currency, $uploadedPrimaryLogo, $uploadedSecondaryLogo);
                
                $headers = "MIME-Version: 1.0\r\n";
                $headers .= "Content-type:text/html;charset=UTF-8\r\n";
                $headers .= "From: $senderName <official@tradewavett.xyz>\r\n";
                
                if (mail($user['email'], $subject, $emailContent, $headers)) {
                    $successCount++;
                } else {
                    $failCount++;
                    $errorMessages[] = "Failed to send to {$user['email']}";
                }
                
            } catch (Exception $e) {
                $failCount++;
                $errorMessages[] = "Error: " . $e->getMessage();
            }
        }
        
        if ($successCount > 0) {
            echo json_encode([
                'success' => true,
                'message' => "✅ Email sent to $successCount recipient(s)!" . ($failCount > 0 ? " ⚠️ Failed: $failCount" : "")
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => "❌ Failed to send emails",
                'details' => $errorMessages
            ]);
        }
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
    exit();
}

// Handle Logo Upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_upload_logo'])) {
    header('Content-Type: application/json');
    
    $uploadDir = 'uploads/logos/';
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
    
    $response = ['success' => false];
    
    try {
        if (isset($_FILES['primary_logo']) && $_FILES['primary_logo']['error'] === 0) {
            $fileName = time() . '_primary_' . basename($_FILES['primary_logo']['name']);
            $targetPath = $uploadDir . $fileName;
            if (move_uploaded_file($_FILES['primary_logo']['tmp_name'], $targetPath)) {
                $response['primaryLogo'] = $targetPath;
            }
        }
        
        if (isset($_FILES['secondary_logo']) && $_FILES['secondary_logo']['error'] === 0) {
            $fileName = time() . '_secondary_' . basename($_FILES['secondary_logo']['name']);
            $targetPath = $uploadDir . $fileName;
            if (move_uploaded_file($_FILES['secondary_logo']['tmp_name'], $targetPath)) {
                $response['secondaryLogo'] = $targetPath;
            }
        }
        
        $response['success'] = true;
        $response['message'] = 'Logos uploaded successfully!';
    } catch (Exception $e) {
        $response['message'] = 'Upload error: ' . $e->getMessage();
    }
    
    echo json_encode($response);
    exit();
}
?>