<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include("check_installation.php");
include("fetch_settings.php");

// ---------------------------------------------------
// PHPMailer Setup (Manual Inclusion)
// ---------------------------------------------------
if (file_exists('PHPMailer/src/PHPMailer.php')) {
    require_once 'PHPMailer/src/Exception.php';
    require_once 'PHPMailer/src/PHPMailer.php';
    require_once 'PHPMailer/src/SMTP.php';
} else {
    die("
    <div style='font-family: sans-serif; padding: 40px; text-align: center; border: 1px solid red; margin: 20px; background: #fff0f0;'>
        <h2 style='color: red;'>Library Missing</h2>
        <p>The PHPMailer library is not installed.</p>
        <p>Please create a folder named <b>PHPMailer</b> inside your <b>admin</b> directory and upload the <b>src</b> folder into it.</p>
    </div>
    ");
}

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

if (!isset($_SESSION["adminid"])) {
    header("Location: login.php");
    exit;
}

// ---------------------------------------------------
// CONFIGURATION
// ---------------------------------------------------
 $smtp_host = 'mail.firstmobilex.click';
 $smtp_username = 'help@firstmobilex.click';
 $smtp_password = 'RzY!wtbiwKzw~g@0';
 $smtp_port = 587;
 $smtp_encryption = 'tls';
 $from_name = 'Firstmobilex Team';
 $from_email = 'help@firstmobilex.click';

// ---------------------------------------------------
// HANDLE EMAIL SENDING
// ---------------------------------------------------
 $message_sent = false;
 $error_msg = '';

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['send_email'])) {
    $subject = trim($_POST['subject']);
    $body = trim($_POST['body']);
    $selected_ids = $_POST['selected_customers'] ?? [];

    if (empty($subject) || empty($body)) {
        $error_msg = "Subject and Body are required.";
    } elseif (empty($selected_ids)) {
        $error_msg = "Please select at least one customer to email.";
    } else {
        $ids_safe = array_map(function($id) use ($con) {
            return (int)$id; 
        }, $selected_ids);
        
        $ids_list = implode(',', $ids_safe);

        $email_sql = "SELECT customerid, firstname, lastname, email FROM customers WHERE customerid IN ($ids_list)";
        $email_res = $con->query($email_sql);
        
        $count_sent = 0;
        $count_fail = 0;

        $mail = new PHPMailer(true);
        
        try {
            $mail->SMTPDebug = SMTP::DEBUG_OFF; 
            $mail->isSMTP();
            $mail->Host       = $smtp_host;
            $mail->SMTPAuth   = true;
            $mail->Username   = $smtp_username;
            $mail->Password   = $smtp_password;
            $mail->SMTPSecure = ($smtp_encryption == 'ssl') ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port       = $smtp_port;
            
            $mail->setFrom($from_email, $from_name);
            $mail->addReplyTo($from_email, $from_name);
            
            $mail->isHTML(true);

            while ($row = $email_res->fetch_assoc()) {
                $mail->clearAddresses();
                $mail->addAddress($row['email'], $row['firstname'] . ' ' . $row['lastname']);
                $mail->Subject = $subject;

                // --- MODERN EMAIL TEMPLATE ---
                $personalized_body = '
                <!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                </head>
                <body style="margin: 0; padding: 0; background-color: #f3f4f6; font-family: Arial, Helvetica, sans-serif;">
                    <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="background-color: #f3f4f6;">
                        <tr>
                            <td align="center" style="padding: 40px 0;">
                                <table role="presentation" width="600" cellspacing="0" cellpadding="0" border="0" style="background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 6px rgba(0,0,0,0.05);">
                                    <tr>
                                        <td align="center" style="padding: 30px 40px; background: linear-gradient(135deg, #4e73df 0%, #224abe 100%); background-color: #4e73df;">
                                            <h1 style="margin: 0; color: #ffffff; font-size: 24px; font-weight: 700;">' . htmlspecialchars($from_name) . '</h1>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="padding: 40px 40px 20px 40px;">
                                            <h2 style="margin: 0 0 10px 0; font-size: 20px; color: #333;">Hello ' . htmlspecialchars($row['firstname']) . ',</h2>
                                            <div style="font-size: 16px; line-height: 1.6; color: #555;">' . nl2br(htmlspecialchars($body)) . '</div>
                                        </td>
                                    </tr>
                                    <tr><td style="padding: 30px 40px;"><div style="border-top: 1px solid #e9ecef;"></div></td></tr>
                                    <tr>
                                        <td align="center" style="padding: 0 40px 40px 40px;">
                                            <p style="margin: 0; font-size: 13px; color: #858796;">Thank you for choosing us.<br><strong>The ' . htmlspecialchars($from_name) . ' Team</strong></p>
                                            <br>
                                            <a href="https://firstmobilex.click" style="font-size: 12px; color: #4e73df; text-decoration: none;">www.firstmobilex.click</a>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                </body>
                </html>';
                
                $mail->Body = $personalized_body;
                $mail->AltBody = "Dear " . $row['firstname'] . ", " . strip_tags($body);

                if($mail->send()){
                    $count_sent++;
                } else {
                    $count_fail++;
                }
            }

            // --- UPDATED: Set Session Variables for Modern Alert ---
            $_SESSION['toast_sent'] = $count_sent;
            $_SESSION['toast_fail'] = $count_fail;
            // Determine type based on results
            if($count_sent > 0 && $count_fail == 0) {
                $_SESSION['toast_type'] = 'success';
            } elseif($count_sent > 0 && $count_fail > 0) {
                $_SESSION['toast_type'] = 'warning';
            } else {
                $_SESSION['toast_type'] = 'error';
            }

            header("Location: email_manager.php");
            exit;

        } catch (Exception $e) {
            $error_msg = "Message could not be sent. Mailer Error: " . $mail->ErrorInfo;
        }
    }
}

// ---------------------------------------------------
// FETCH CUSTOMERS
// ---------------------------------------------------
 $records_per_page = 10;
 $current_page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
 $offset = ($current_page - 1) * $records_per_page;

 $total_result = $con->query("SELECT COUNT(*) FROM customers WHERE regstatus = 'visible'");
 $total_rows = $total_result->fetch_row()[0];
 $total_pages = ceil($total_rows / $records_per_page);

 $sql = "SELECT customerid, loginid, firstname, lastname, email, accstatus FROM customers WHERE regstatus = 'visible' ORDER BY customerid DESC LIMIT $records_per_page OFFSET $offset";
 $result = $con->query($sql);
 $customers = $result->fetch_all(MYSQLI_ASSOC);
 $result->free();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Email Manager</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
    <link rel="icon" href="../<?= htmlspecialchars($system_favicon ?? ''); ?>" type="image/<?= pathinfo($system_favicon ?? 'favicon.ico', PATHINFO_EXTENSION); ?>">
    <link rel="preconnect" href="https://fonts.googleapis.com/">
    <link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&amp;family=Poppins:wght@400;500;700&amp;display=swap">
    <link rel="stylesheet" type="text/css" href="assets/vendor/font-awesome/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/bootstrap-icons/bootstrap-icons.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/overlay-scrollbar/css/overlayscrollbars.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>
<body>

<main>
    <?php include "include/sidebar.php" ?>
    <div class="page-content">
        <?php include "include/topbar.php" ?>
        <div class="page-content-wrapper p-xxl-4">

            <div class="row">
                <div class="col-12 mb-4">
                    <div class="d-sm-flex justify-content-between align-items-center">
                        <h1 class="h3 mb-2 mb-sm-0">Email Manager</h1>
                    </div>
                    <p class="text-muted mb-0">Select users from the list below and compose your message.</p>
                </div>
            </div>

            <!-- UPDATED: Modern Toast Notification Logic -->
            <?php if (isset($_SESSION['toast_sent'])): ?>
                <?php 
                    $sent = $_SESSION['toast_sent'];
                    $fail = $_SESSION['toast_fail'];
                    $type = $_SESSION['toast_type'];
                    
                    // Set icons and titles based on result
                    if ($type == 'success') {
                        $icon = 'success';
                        $title = 'All Emails Sent!';
                        $icon_color = '#28a745';
                    } elseif ($type == 'warning') {
                        $icon = 'warning';
                        $title = 'Partially Completed';
                        $icon_color = '#ffc107';
                    } else {
                        $icon = 'error';
                        $title = 'Sending Failed';
                        $icon_color = '#dc3545';
                    }
                ?>
                <script>
                    document.addEventListener('DOMContentLoaded', function() {
                        Swal.fire({
                            icon: '<?= $type; ?>',
                            title: '<?= $title; ?>',
                            html: `
                                <div style="font-size: 15px; text-align: left; padding: 10px 20px;">
                                    <div style="margin-bottom: 10px;">
                                        <i class="fas fa-check-circle" style="color: #28a745; margin-right: 8px;"></i>
                                        <strong>Sent:</strong> <span style="float: right;"><?= $sent; ?></span>
                                    </div>
                                    <div style="margin-bottom: 0;">
                                        <i class="fas fa-times-circle" style="color: #dc3545; margin-right: 8px;"></i>
                                        <strong>Failed:</strong> <span style="float: right;"><?= $fail; ?></span>
                                    </div>
                                </div>
                            `,
                            showConfirmButton: true,
                            confirmButtonText: 'Okay',
                            confirmButtonColor: '#4e73df',
                            showClass: {
                                popup: 'animate__animated animate__fadeInDown'
                            },
                            hideClass: {
                                popup: 'animate__animated animate__fadeOutUp'
                            }
                        });
                    });
                </script>
                <?php 
                    unset($_SESSION['toast_sent']); 
                    unset($_SESSION['toast_fail']); 
                    unset($_SESSION['toast_type']); 
                ?>
            <?php endif; ?>

            <?php if ($error_msg): ?>
                <div class="alert alert-danger"><?= $error_msg; ?></div>
            <?php endif; ?>

            <form method="POST" action="">
                <div class="card shadow mb-4 border-primary">
                    <div class="card-header bg-white">
                        <h5 class="mb-0"><i class="fas fa-envelope me-2"></i> Compose Email</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label fw-bold">Subject</label>
                            <input type="text" name="subject" class="form-control" placeholder="Enter email subject..." required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Message</label>
                            <textarea name="body" class="form-control" rows="5" placeholder="Type your message here..." required></textarea>
                        </div>
                        <div class="d-flex justify-content-end gap-2">
                            <button type="submit" name="send_email" class="btn btn-primary">
                                <i class="fas fa-paper-plane me-2"></i> Send to Selected
                            </button>
                        </div>
                    </div>
                </div>

                <div class="card shadow">
                    <div class="card-header border-bottom d-flex justify-content-between align-items-center">
                        <h5 class="card-title mb-0">Select Recipients</h5>
                        <button type="button" id="selectAllBtn" class="btn btn-sm btn-outline-secondary">
                            Select All on Page
                        </button>
                    </div>
                    <div class="card-body">
                        
                        <div class="bg-light rounded p-3 d-none d-lg-block">
                            <div class="row g-4">
                                <div class="col-lg-1"><input type="checkbox" id="checkAllMain" class="form-check-input"></div>
                                <div class="col-lg-2"><h6 class="mb-0">ID</h6></div>
                                <div class="col-lg-3"><h6 class="mb-0">Name</h6></div>
                                <div class="col-lg-4"><h6 class="mb-0">Email</h6></div>
                                <div class="col-lg-2"><h6 class="mb-0">Status</h6></div>
                            </div>
                        </div>

                        <?php if (!empty($customers)): ?>
                            <?php foreach ($customers as $customer): ?>
                                <?php
                                $status_class = $customer['accstatus'] == 'active' ? 'bg-success text-white' : 'bg-secondary';
                                ?>
                                <div class="row g-4 align-items-center border-bottom px-2 py-3 hover-bg-light">
                                    <div class="col-1 d-none d-lg-block text-center">
                                        <input type="checkbox" name="selected_customers[]" value="<?= $customer['customerid']; ?>" class="form-check-input customer-checkbox">
                                    </div>
                                    
                                    <div class="col-12 d-lg-none">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div class="form-check">
                                                <input type="checkbox" name="selected_customers[]" value="<?= $customer['customerid']; ?>" class="form-check-input customer-checkbox">
                                                <label class="form-check-label fw-bold">
                                                    <?= htmlspecialchars($customer['firstname'] . " " . $customer['lastname']); ?>
                                                </label>
                                            </div>
                                            <span class="badge <?= $status_class; ?>"><?= ucfirst($customer['accstatus']); ?></span>
                                        </div>
                                        <small class="text-muted d-block mt-1">ID: <?= $customer['customerid']; ?> | <?= htmlspecialchars($customer['email']); ?></small>
                                    </div>

                                    <div class="col-lg-2 d-none d-lg-block">
                                        <h6 class="mb-0 fw-normal"><?= htmlspecialchars($customer['customerid']); ?></h6>
                                    </div>
                                    <div class="col-lg-3 d-none d-lg-block">
                                        <h6 class="mb-0 fw-normal"><?= htmlspecialchars($customer['firstname'] . " " . $customer['lastname']); ?></h6>
                                    </div>
                                    <div class="col-lg-4 d-none d-lg-block">
                                        <h6 class="mb-0 fw-normal text-truncate"><?= htmlspecialchars($customer['email']); ?></h6>
                                    </div>
                                    <div class="col-lg-2 d-none d-lg-block">
                                        <span class="badge <?= $status_class; ?>"><?= ucfirst($customer['accstatus']); ?></span>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div class="text-center py-5 text-muted">
                                <i class="fas fa-users-slash fa-3x mb-3"></i>
                                <p>No customers found.</p>
                            </div>
                        <?php endif; ?>

                    </div>
                    
                    <div class="card-footer pt-0">
                        <div class="d-sm-flex justify-content-sm-between align-items-sm-center">
                            <p class="mb-sm-0 text-center text-sm-start">
                                Showing <?= min($offset + 1, $total_rows); ?> to <?= min($offset + $records_per_page, $total_rows); ?> of <?= $total_rows; ?> entries
                            </p>
                            <nav class="mb-sm-0 d-flex justify-content-center" aria-label="navigation">
                                <ul class="pagination pagination-sm pagination-primary-soft mb-0">
                                    <li class="page-item <?= ($current_page <= 1) ? 'disabled' : ''; ?>">
                                        <a class="page-link" href="?page=<?= max(1, $current_page - 1); ?>">Prev</a>
                                    </li>
                                    <?php for ($p = 1; $p <= $total_pages; $p++): ?>
                                        <li class="page-item <?= ($p == $current_page) ? 'active' : ''; ?>">
                                            <a class="page-link" href="?page=<?= $p; ?>"><?= $p; ?></a>
                                        </li>
                                    <?php endfor; ?>
                                    <li class="page-item <?= ($current_page >= $total_pages) ? 'disabled' : ''; ?>">
                                        <a class="page-link" href="?page=<?= min($total_pages, $current_page + 1); ?>">Next</a>
                                    </li>
                                </ul>
                            </nav>
                        </div>
                    </div>
                </div>
            </form>

        </div>
    </div>
</main>

<script src="assets/vendor/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/overlay-scrollbar/js/overlayscrollbars.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const mainCheckbox = document.getElementById('checkAllMain');
        const checkboxes = document.querySelectorAll('.customer-checkbox');
        const selectAllBtn = document.getElementById('selectAllBtn');

        mainCheckbox.addEventListener('change', function() {
            checkboxes.forEach(cb => {
                cb.checked = mainCheckbox.checked;
            });
        });

        selectAllBtn.addEventListener('click', function() {
            const allChecked = Array.from(checkboxes).every(cb => cb.checked);
            checkboxes.forEach(cb => {
                cb.checked = !allChecked;
            });
            mainCheckbox.checked = !allChecked;
        });
    });
</script>
</body>
</html>