<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Use correct config path
$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (file_exists($config_path)) {
    include($config_path);
} else {
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}

// Set JSON response type
header('Content-Type: application/json');

// ═══════════════════════════════════════════════════════════════
//  SMTP CONFIGURATION - use settings stored in the database
// ═══════════════════════════════════════════════════════════════
$smtp_config = get_mail_settings($pdo, $site_data);

$smtp_config['host']       = trim($smtp_config['smtp_host'] ?? '');
$smtp_config['port']       = intval($smtp_config['smtp_port'] ?? 587);
$smtp_config['encryption'] = trim($smtp_config['smtp_encryption'] ?? 'tls');
$smtp_config['username']   = trim($smtp_config['smtp_username'] ?? '');
$smtp_config['password']   = trim($smtp_config['smtp_password'] ?? '');
$smtp_config['from_email'] = trim($smtp_config['smtp_from_email'] ?? $site_data['web_email'] ?? '');
$smtp_config['from_name']  = trim($smtp_config['smtp_from_name'] ?? $site_data['web_name'] ?? 'Website');

if (empty($smtp_config['host']) || empty($smtp_config['username']) || empty($smtp_config['password'])) {
    echo json_encode(['status' => '0', 'msg' => 'SMTP settings are not configured in the database. Please update them in admin settings.']);
    exit();
}

// Verify admin status
$stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin || $admin['is_admin'] != 1) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized access']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
    exit();
}

// Get form data
$recipient_type = isset($_POST['recipient_type']) ? trim($_POST['recipient_type']) : '';
$subject = isset($_POST['subject']) ? trim($_POST['subject']) : '';
$message = isset($_POST['message']) ? trim($_POST['message']) : '';

// Validate inputs
if (empty($subject)) {
    echo json_encode(['status' => '0', 'msg' => 'Email subject is required']);
    exit();
}

if (empty($message)) {
    echo json_encode(['status' => '0', 'msg' => 'Email message is required']);
    exit();
}

if (!in_array($recipient_type, ['individual', 'all'])) {
    echo json_encode(['status' => '0', 'msg' => 'Invalid recipient type']);
    exit();
}

// Get recipient emails
$recipients = [];

try {
    if ($recipient_type === 'all') {
        $stmt = $pdo->prepare("SELECT id, email, username, full_name FROM users WHERE status = 1");
        $stmt->execute();
        $recipients = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $user_ids = isset($_POST['user_ids']) ? $_POST['user_ids'] : [];
        
        if (empty($user_ids)) {
            echo json_encode(['status' => '0', 'msg' => 'Please select at least one recipient']);
            exit();
        }

        $user_ids = array_map('intval', $user_ids);
        $placeholders = implode(',', array_fill(0, count($user_ids), '?'));
        
        $stmt = $pdo->prepare("SELECT id, email, username, full_name FROM users WHERE id IN ($placeholders) AND status = 1");
        $stmt->execute($user_ids);
        $recipients = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (PDOException $e) {
    echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    exit();
}

if (empty($recipients)) {
    echo json_encode(['status' => '0', 'msg' => 'No valid recipients found']);
    exit();
}

// Build HTML email template
$logo_url = !empty($site_data['logo_url']) ? $site_data['logo_url'] : $site_data['web_url'] . '/images/softbills.png';
$web_url = $site_data['web_url'];
$web_email = $site_data['web_email'];
$whatsapp_number = '2349162671360';
if (!empty($site_data['whatsapp_number'])) {
    $whatsapp_number = preg_replace('/[^0-9]/', '', $site_data['whatsapp_number']);
} elseif (!empty($site_data['support_url'])) {
    // If support_url is a wa.me link, extract the number
    if (strpos($site_data['support_url'], 'wa.me') !== false) {
        $whatsapp_number = preg_replace('/[^0-9]/', '', $site_data['support_url']);
    }
}
$whatsapp_link = 'https://wa.me/' . $whatsapp_number;

$email_body = '<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>' . htmlspecialchars($subject) . '</title>
</head>
<body style="font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Arial, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; background-color: #f0f2f5;">
    <div style="max-width: 600px; margin: 30px auto; background: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.08);">
        
        <!-- Header with Logo -->
        <div style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%); padding: 30px; text-align: center;">
            <img src="' . htmlspecialchars($logo_url) . '" alt="' . htmlspecialchars($smtp_config['from_name']) . '" style="max-width: 120px; max-height: 60px; margin-bottom: 12px;">
            <h1 style="margin: 0; font-size: 20px; color: #ffffff; font-weight: 600;">' . htmlspecialchars($smtp_config['from_name']) . '</h1>
        </div>

        <!-- Email Body Content -->
        <div style="padding: 35px 30px;">
            ' . $message . '
        </div>

        <!-- WhatsApp Button -->
        <div style="padding: 0 30px 15px; text-align: center;">
            <a href="' . $whatsapp_link . '" target="_blank" style="display: inline-block; background-color: #25D366; color: #ffffff; text-decoration: none; padding: 14px 32px; border-radius: 50px; font-size: 15px; font-weight: 600; box-shadow: 0 4px 12px rgba(37,211,102,0.3);">
                &#128172; Chat on WhatsApp
            </a>
        </div>

        <!-- Telegram Button -->
        <div style="padding: 0 30px 30px; text-align: center;">
            <p style="margin: 0 0 10px; font-size: 14px; font-weight: 600; color: #333;">Join Our Telegram Group</p>
            <p style="margin: 0 0 14px; font-size: 12px; color: #6c757d;">Get updates, support &amp; exclusive offers</p>
            <a href="' . htmlspecialchars($site_data['channel_url'] ?? '') . '" target="_blank" style="display: inline-block; background-color: #0088cc; color: #ffffff; text-decoration: none; padding: 14px 32px; border-radius: 50px; font-size: 15px; font-weight: 600; box-shadow: 0 4px 12px rgba(0,136,204,0.3);">
                &#9992; Join Telegram
            </a>
        </div>

        <!-- Footer -->
        <div style="background: #f8f9fc; padding: 25px 30px; text-align: center; border-top: 1px solid #e3e6f0;">
            <p style="margin: 0 0 8px; font-size: 13px; color: #6c757d;">
                <a href="' . htmlspecialchars($web_url) . '" style="color: #4e73df; text-decoration: none; font-weight: 600;">' . htmlspecialchars($web_url) . '</a>
            </p>
            <p style="margin: 0 0 8px; font-size: 13px; color: #6c757d;">
                &#9993; <a href="mailto:' . htmlspecialchars($web_email) . '" style="color: #4e73df; text-decoration: none;">' . htmlspecialchars($web_email) . '</a>
            </p>
            <p style="margin: 12px 0 0; font-size: 11px; color: #adb5bd;">
                &copy; ' . date('Y') . ' ' . htmlspecialchars($smtp_config['from_name']) . '. All rights reserved.
            </p>
        </div>

    </div>
</body>
</html>';

// Send emails using PHPMailer
$sent_count = 0;
$failed_count = 0;
$error_messages = [];

foreach ($recipients as $recipient) {
    $to = $recipient['email'];
    
    if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
        $failed_count++;
        continue;
    }

    try {
        $mail_sent = send_system_email($to, $subject, $email_body, $pdo, $site_data, [
            'from_email' => $smtp_config['from_email'],
            'from_name' => $smtp_config['from_name'],
        ]);

        if ($mail_sent) {
            $sent_count++;
        } else {
            $failed_count++;
            $error_messages[] = $to . ': failed';
        }

    } catch (\PHPMailer\PHPMailer\Exception $e) {
        $failed_count++;
        $error_messages[] = $to . ': ' . $e->getMessage();
    }

    // Small delay for bulk sends
    if (count($recipients) > 10) {
        usleep(200000); // 200ms delay
    }
}

// Return result
if ($sent_count > 0) {
    $msg = "Email sent successfully to <strong>{$sent_count}</strong> recipient(s).";
    if ($failed_count > 0) {
        $msg .= "<br><small class='text-warning'>Failed to send to {$failed_count} recipient(s).</small>";
    }
    echo json_encode(['status' => '1', 'msg' => $msg, 'sent' => $sent_count, 'failed' => $failed_count]);
} else {
    $error_detail = !empty($error_messages) ? '<br><small>' . htmlspecialchars($error_messages[0]) . '</small>' : '';
    echo json_encode(['status' => '0', 'msg' => 'Failed to send emails. Please check your SMTP configuration.' . $error_detail]);
}
?>
