<?php
// Must be at the very top - NO SPACE OR OUTPUT BEFORE THIS
session_start();

// Now include DB & header
include "../include/db.php";
include "include/header.php";

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

// Load PHPMailer
require 'vendor/PHPMailer/src/Exception.php';
require 'vendor/PHPMailer/src/PHPMailer.php';
require 'vendor/PHPMailer/src/SMTP.php';

$success = '';
$errors = [];
$sent_count = 0;
$total_users = 0;

// Fetch total users
$total_stmt = $conn->query("SELECT COUNT(*) as total FROM users WHERE email != '' AND email IS NOT NULL");
$total_row = $total_stmt->fetch_assoc();
$total_users = $total_row['total'];

// Handle Bulk Send
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_bulk'])) {
    $subject = trim($_POST['subject'] ?? '');
    $message = trim($_POST['message'] ?? '');

    if (empty($subject)) {
        $errors[] = 'বিষয় প্রয়োজন';
    }
    if (empty($message)) {
        $errors[] = 'বার্তা প্রয়োজন';
    }

    if (empty($errors)) {
        $stmt = $conn->prepare("SELECT name, email FROM users WHERE email != '' AND email IS NOT NULL");
        $stmt->execute();
        $result = $stmt->get_result();
        $users = $result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();

        if (empty($users)) {
            $errors[] = 'কোনো বৈধ ইমেইল পাওয়া যায়নি';
        } else {
            $mail = new PHPMailer(true);
            try {
                $mail->isSMTP();
                $mail->Host       = 'mail.itgalaxy.academy';
                $mail->SMTPAuth   = true;
                $mail->Username   = 'support@itgalaxy.academy';
                $mail->Password   = getenv('SMTP_PASSWORD') ?: '*01723624071#';
                $mail->SMTPSecure = 'tls';
                $mail->Port       = 587;
                $mail->CharSet    = 'UTF-8';

                $mail->setFrom('support@itgalaxy.academy', 'IT Galaxy Academy');
                $mail->addReplyTo('support@itgalaxy.academy', 'IT Galaxy Academy');
                $mail->isHTML(true);

                foreach ($users as $user) {
                    $to_email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
                    if (!filter_var($to_email, FILTER_VALIDATE_EMAIL)) continue;

                    $mail->clearAddresses();
                    $mail->addAddress($to_email, $user['name'] ?? '');
                    $mail->Subject = $subject;

                    $mail->Body = "
                        <html>
                        <body style='font-family: Arial, sans-serif; color: #333; line-height: 1.6;'>
                            <div style='max-width: 600px; margin: 20px auto; padding: 20px; border: 1px solid #eee; border-radius: 12px; background: #fff;'>
                                <h2 style='color: #1A237E; text-align: center; margin-bottom: 20px;'>IT Galaxy Academy</h2>
                                <hr style='border: 1px solid #ddd; margin: 20px 0;'>
                                <p><strong>প্রিয় {$user['name']},</strong></p>
                                <div style='background: #fff8e1; padding: 18px; border-left: 5px solid #FF8F00; margin: 20px 0; border-radius: 8px; font-size: 15px;'>
                                    " . nl2br(htmlspecialchars($message)) . "
                                </div>
                                <p>ধন্যবাদ,<br><strong>IT Galaxy Academy Team</strong></p>
                                <hr style='border: 1px solid #ddd; margin: 30px 0 20px;'>
                                <p style='font-size: 12px; color: #888; text-align: center;'>
                                    © " . date('Y') . " IT Galaxy Academy. All rights reserved.<br>
                                    <a href='https://itgalaxy.academy' style='color: #FF5722; text-decoration: none;'>www.itgalaxy.academy</a>
                                </p>
                            </div>
                        </body>
                        </html>
                    ";

                    if ($mail->send()) {
                        $sent_count++;
                    }
                }

                $success = "সফলভাবে $sent_count জন ইউজারকে ইমেইল পাঠানো হয়েছে! (মোট: $total_users)";
            } catch (Exception $e) {
                $errors[] = 'ইমেইল পাঠাতে ব্যর্থ: ' . $mail->ErrorInfo;
            }
        }
    }

    // Flash message
    if ($success) {
        $_SESSION['result'] = $success;
        $_SESSION['status'] = 'ok';
    } elseif (!empty($errors)) {
        $_SESSION['result'] = implode('<br>', $errors);
        $_SESSION['status'] = 'error';
    }
    header("Location: bulk_mail.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>বাল্ক ইমেইল - IT Galaxy Academy</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;600&family=Roboto:wght@700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background: #f8fafc;
            color: #333;
        }
        .content {
            margin-left: 250px;
            padding: 2rem;
            min-height: 100vh;
        }
        .card {
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.08);
            overflow: hidden;
        }
        .card-header {
            background: linear-gradient(135deg, #1E293B 0%, #334155 100%);
            color: white;
            padding: 1.5rem;
        }
        .card-header h2 {
            font-family: 'Roboto', sans-serif;
            font-weight: 700;
        }
        .form-control, .form-control:focus {
            border-radius: 8px;
            padding: 12px;
            box-shadow: none;
        }
        .btn-primary {
            background: linear-gradient(45deg, #FF5722, #FF8A65);
            border: none;
            padding: 14px 32px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 1.1rem;
            transition: all 0.3s;
        }
        .btn-primary:hover {
            background: linear-gradient(45deg, #E64A19, #FF7043);
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(255, 87, 34, 0.3);
        }
        .btn-back {
            background: #6c757d;
            color: white;
            padding: 12px 20px;
            border-radius: 8px;
            text-decoration: none;
            display: inline-block;
        }
        .info-box {
            background: #e0f2fe;
            border-left: 5px solid #0ea5e9;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 15px;
        }
        .alert {
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        @media (max-width: 768px) {
            .content { margin-left: 0; padding: 1rem; }
            .card-header { padding: 1rem; }
            .btn-primary { font-size: 1rem; padding: 12px 24px; }
        }
    </style>
</head>
<body>
    <!-- Top Nav -->
    <nav class="top-nav sticky top-0 text-white p-4 flex justify-between items-center shadow-lg z-40 backdrop-blur-md bg-white/10">
        <div class="logo text-2xl font-bold">CourseLMS Admin</div>
        <div>
            <a href="contacts.php" class="btn-back">
                Back to Messages
            </a>
        </div>
    </nav>

    <div class="content">
        <div class="max-w-4xl mx-auto">
            <div class="card">
                <div class="card-header">
                    <h2 class="mb-0">বাল্ক ইমেইল পাঠান</h2>
                    <p class="mb-0 opacity-90">সকল ইউজারকে একসাথে অফার/নোটিফিকেশন পাঠান</p>
                </div>

                <div class="card-body p-4">
                    <!-- Info Box -->
                    <div class="info-box">
                        <strong>মোট ইউজার:</strong> <?php echo $total_users; ?> জন
                        <br><small class="text-muted">শুধুমাত্র বৈধ ইমেইল থাকা ইউজারদের পাঠানো হবে</small>
                    </div>

                    <!-- Session Message -->
                    <?php if (isset($_SESSION['status'])): ?>
                        <div class="alert alert-<?php echo $_SESSION['status'] == 'ok' ? 'success' : 'danger'; ?>">
                            <?php 
                            echo $_SESSION['result']; 
                            unset($_SESSION['result'], $_SESSION['status']);
                            ?>
                        </div>
                    <?php endif; ?>

                    <!-- Bulk Mail Form -->
                    <form method="POST" onsubmit="return confirm('আপনি কি সকল ইউজারকে ইমেইল পাঠাতে চান?');">
                        <div class="mb-3">
                            <label class="form-label fw-bold">বিষয়</label>
                            <input type="text" name="subject" class="form-control" placeholder="যেমন: স্পেশাল ডিসকাউন্ট অফার!" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-bold">বার্তা (অফার/নোটিফিকেশন)</label>
                            <textarea name="message" class="form-control" rows="10" placeholder="আপনার বার্তা লিখুন... (ইউজারের নাম স্বয়ংক্রিয়ভাবে যোগ হবে)" required></textarea>
                        </div>

                        <div class="d-flex gap-3">
                            <button type="submit" name="send_bulk" class="btn btn-primary">
                                Send to All Users
                            </button>
                            <a href="contacts.php" class="btn btn-back">
                                Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <?php include "include/footer.php"; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>