<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

require_once 'php/adminconfig.php';
require_once 'PHPMailer-master/src/Exception.php';
require_once 'PHPMailer-master/src/PHPMailer.php';
require_once 'PHPMailer-master/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['userIds']) || empty($input['userIds'])) {
    echo json_encode(['success' => false, 'message' => 'No users selected']);
    exit;
}

$userIds = $input['userIds'];
$successCount = 0;
$errors = [];

try {
    // Get user details
    $placeholders = str_repeat('?,', count($userIds) - 1) . '?';
    $query = "SELECT id, firstname, lastname, email FROM users WHERE id IN ($placeholders)";
    $stmt = $conn->prepare($query);
    $stmt->execute($userIds);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($users as $user) {
        try {
            $fullName = $user['firstname'] . ' ' . $user['lastname'];
            $subject = "AML Tariff Notice";
            
            // Create email content with logos
            $message = '
            <html>
            <head>
                <meta charset="UTF-8">
                <style>
                    body { 
                        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; 
                        line-height: 1.7; 
                        color: #2c3e50; 
                        max-width: 600px; 
                        margin: 0 auto; 
                        background: #ffffff;
                        padding: 0;
                    }
                    .container {
                        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
                        border-radius: 8px;
                        overflow: hidden;
                        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
                    }
                    .header { 
                        text-align: center; 
                        margin-bottom: 0; 
                        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                        padding: 15px 20px;
                        color: white;
                    }
                    .logos { 
                        display: flex; 
                        justify-content: center; 
                        align-items: center; 
                        gap: 10px; 
                        margin-bottom: 5px; 
                    }
                    .logos img { 
                        width: 50px; 
                        height: 50px; 
                        border-radius: 10%; 
                        object-fit: contain; 
                        background: white;
                        padding: 2px;
                        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                    }

                    .the-religion {
                        height: 80px !important;
                        width: 80px !important;
                    }
                    .header-text {
                        font-size: 16px;
                        font-weight: 300;
                        opacity: 0.95;
                        margin: 0;
                    }
                    .content { 
                        padding: 20px 15px; 
                        background: white;
                    }
                    .greeting {
                        font-size: 15px;
                        font-weight: 500;
                        color: #1a73e8;
                        margin-bottom: 10px;
                    }
                    .subject-line {
                        background: #f8f9fa;
                        border-left: 4px solid #1a73e8;
                        padding: 12px 16px;
                        margin: 10px 0;
                        font-weight: 600;
                        border-radius: 0 8px 8px 0;
                    }

                    .content p {
                        font-size: 13px;
                    }
                    .fee-box {
                        background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
                        border: 1px solid #ffc107;
                        border-radius: 8px;
                        padding: 20px;
                        margin: 25px 0;
                        text-align: center;
                    }
                    .fee-amount {
                        font-size: 24px;
                        font-weight: 700;
                        color: #d63384;
                        margin: 10px 0;
                    }
                    .details-box {
                        background: #f8f9fa;
                        border-radius: 8px;
                        padding: 20px;
                        margin: 20px 0;
                        border: 1px solid #e9ecef;
                    }
                    ul { 
                        margin: 0; 
                        padding-left: 20px; 
                        list-style-type: none;
                    }
                    ul li {
                        position: relative;
                        padding-left: 20px;
                        margin-bottom: 8px;
                        color: #495057;
                        font-size: 12px;
                    }
                    ul li:before {
                        content: "•";
                        color: #1a73e8;
                        font-weight: 700;
                        position: absolute;
                        left: 0;
                    }
                    .signature { 
                        margin-top: 40px; 
                        padding-top: 25px;
                        border-top: 2px solid #e9ecef;
                        background: #f8f9fa;
                        border-radius: 8px;
                        padding: 25px;
                    }
                    .signature-title {
                        color: #1a73e8;
                        font-weight: 600;
                        margin-bottom: 8px;
                    }
                    .company-name {
                        font-weight: 600;
                        color: #495057;
                        line-height: 1.4;
                    }
                    .important-note {
                        background: #e3f2fd;
                        border-left: 4px solid #2196f3;
                        padding: 15px;
                        margin: 20px 0;
                        border-radius: 0 8px 8px 0;
                        font-style: italic;
                        color: #1565c0;
                        font-size: 11px;
                    }
                </style>
            </head>
            <body>
                <div class="container">
                    <div class="header">
                        <div class="logos">
                            <img src="https://tradewave.ifctrades.live/ifctrading/images/frc-logo.png" alt="FSC Logo" class="the-religion">
                            <img src="https://tradewave.ifctrades.live/ifctrading/images/icon.png" alt="TradeWave Logo">
                        </div>
                        <p class="header-text">Financial Services Commission (FSC)</p>
                    </div>
                    
                    <div class="content">
                        <p class="greeting">Dear ' . htmlspecialchars($fullName) . ',</p>
                        
                        <div class="subject-line">
                            <strong>Re: Withdrawal Request from Trading Account</strong>
                        </div>
                        
                        <p>We are writing to inform you that due to additional scrutiny required by the <strong>Financial Services Commission (FSC) of Trinidad and Tobago</strong>, the regulatory body overseeing trading activities in the Trinidad and Tobago market, we are obligated to apply an Anti-Money Laundering (AML) tariff to your account.</p>
                        
                        <p>As part of our compliance with the FSCs regulations, we have been required to conduct enhanced due diligence on your account due to the nature of your transactions. This additional scrutiny is aimed at ensuring the integrity of our platform and adherence to international standards.</p>
                        
                        <p>In light of this, we regret to inform you that your current withdrawal request has been put on hold pending settlement of the AML tariff. The fee is necessary to cover the costs associated with the enhanced monitoring and reporting requirements.</p>
                        
                        <div class="fee-box">
                            <p><strong>AML Tariff Fee Required</strong></p>
                            <div class="fee-amount">TTD 10,000.00</div>
                            <p>Once payment is received, we will promptly process your withdrawal request.</p>
                        </div>
                        
                        <div class="details-box">
                            <p><strong>Payment Details:</strong></p>
                            <ul>
                                <li><strong>Fee Amount:</strong> TTD 10,000.00</li>
                                <li><strong>Payment Method:</strong> Select from dashboard</li>
                                <li><strong>Payment Instructions:</strong> Contact support if you can\'t navigate to payment section and need more clarity</li>
                            </ul>
                        </div>
                        
                        <div class="important-note">
                            <strong>Important:</strong> We appreciate your understanding and cooperation in this matter. If you have any questions or concerns, please do not hesitate to reach out to our support team.
                        </div>
                        
                        <p>Thank you for your prompt attention to this matter.</p>
                        
                        <div class="signature">
                            <p class="signature-title">Best regards,</p>
                            <div class="company-name">
                                Trade FSC Commission<br>
                                Tradewave TT Team
                            </div>
                        </div>
                    </div>
                </div>
            </body>
            </html>';
            
            if (send_mail($user['email'], $subject, $message)) {
                $successCount++;
            } else {
                $errors[] = "Failed to send email to " . $user['email'];
            }
            
        } catch (Exception $e) {
            $errors[] = "Error sending to " . $user['email'] . ": " . $e->getMessage();
        }
    }
    
    if ($successCount > 0) {
        echo json_encode([
            'success' => true, 
            'sent' => $successCount, 
            'errors' => $errors
        ]);
    } else {
        echo json_encode([
            'success' => false, 
            'message' => 'Failed to send any emails',
            'errors' => $errors
        ]);
    }
    
} catch(PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}

function send_mail($recipient, $subject, $message)
{
    $mail = new PHPMailer();
    $mail->IsSMTP();

    $mail->SMTPDebug  = 0;  
    $mail->SMTPAuth   = TRUE;
    $mail->SMTPSecure = "tls";
    $mail->Port       = 587;
    $mail->Host       = "mail.ifctrades.live";
    $mail->Username   = "tradewave@ifctrades.live";
    $mail->Password   = "#Trader00#";

    $mail->IsHTML(true);
    $mail->AddAddress($recipient, "Elite Trader");
    $mail->SetFrom("tradewave@ifctrades.live", "FSC Notification");
    $mail->Subject = $subject;
    $mail->Body = $message;

    try {
        return $mail->Send();
    } catch (Exception $e) {
        error_log("Mail Error: " . $e->getMessage());
        return false;
    }
}
?>