<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

include("check_installation.php");
include("fetch_settings.php");
require_once("../config/functions.php");

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

$customers = [];
$resCustomers = $con->query("SELECT customerid, firstname, lastname, email FROM customers ORDER BY firstname ASC, lastname ASC");
while ($row = $resCustomers->fetch_assoc()) {
    $customers[] = $row;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_custom_email'])) {
    $recipientMode = trim($_POST['recipient_mode'] ?? '');
    $customerId = (int) ($_POST['customer_id'] ?? 0);
    $manualEmailsRaw = trim($_POST['manual_emails'] ?? '');
    $subject = trim($_POST['subject'] ?? '');
    $message = trim($_POST['message'] ?? '');

    $targets = [];
    if ($subject === '' || $message === '') {
        $_SESSION['message'] = ['type' => 'error', 'text' => 'Subject and message are required.'];
        header("Location: custom_email.php");
        exit;
    }

    if ($recipientMode === 'single') {
        $stmt = $con->prepare("SELECT email FROM customers WHERE customerid = ? LIMIT 1");
        $stmt->bind_param("i", $customerId);
        $stmt->execute();
        $single = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        if (!empty($single['email']) && filter_var($single['email'], FILTER_VALIDATE_EMAIL)) {
            $targets[] = $single['email'];
        }
    } elseif ($recipientMode === 'all') {
        $resultAll = $con->query("SELECT email FROM customers WHERE email IS NOT NULL AND email <> ''");
        while ($row = $resultAll->fetch_assoc()) {
            if (filter_var($row['email'], FILTER_VALIDATE_EMAIL)) {
                $targets[] = $row['email'];
            }
        }
    } elseif ($recipientMode === 'manual') {
        $parts = preg_split('/[\s,;]+/', $manualEmailsRaw);
        foreach ($parts as $emailPart) {
            $emailPart = trim($emailPart);
            if ($emailPart !== '' && filter_var($emailPart, FILTER_VALIDATE_EMAIL)) {
                $targets[] = $emailPart;
            }
        }
    }

    $targets = array_values(array_unique($targets));
    if (empty($targets)) {
        $_SESSION['message'] = ['type' => 'error', 'text' => 'No valid recipient email found for the selected option.'];
        header("Location: custom_email.php");
        exit;
    }

    $safeSubject = htmlspecialchars($subject, ENT_QUOTES, 'UTF-8');
    $safeMessage = nl2br(htmlspecialchars($message, ENT_QUOTES, 'UTF-8'));
    $mailBody = "
    <!DOCTYPE html>
    <html>
    <head><meta charset='UTF-8'><meta name='viewport' content='width=device-width, initial-scale=1.0'></head>
    <body style='margin:0;padding:0;background:#f8fafc;font-family:Arial,sans-serif;'>
        <table width='100%' cellpadding='0' cellspacing='0' style='padding:30px 15px;'>
            <tr><td align='center'>
                <table width='100%' cellpadding='0' cellspacing='0' style='max-width:640px;background:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 15px rgba(0,0,0,0.05);'>
                    <tr>
                        <td style='background:linear-gradient(135deg,#003399 0%,#005D9D 100%);padding:24px;color:#ffffff;'>
                            <h2 style='margin:0;font-size:22px;'>" . $safeSubject . "</h2>
                        </td>
                    </tr>
                    <tr>
                        <td style='padding:26px;color:#0f172a;line-height:1.7;font-size:15px;'>
                            {$safeMessage}
                            <p style='margin-top:24px;color:#64748b;'>Regards,<br><strong>" . htmlspecialchars($system_bank_name, ENT_QUOTES, 'UTF-8') . "</strong></p>
                        </td>
                    </tr>
                </table>
            </td></tr>
        </table>
    </body>
    </html>
    ";

    $sentCount = 0;
    foreach ($targets as $toEmail) {
        if (sendMail($toEmail, $subject, $mailBody)) {
            $sentCount++;
        }
    }

    if ($sentCount === 0) {
        $_SESSION['message'] = ['type' => 'error', 'text' => 'Mail could not be sent. Check SMTP settings and try again.'];
    } elseif ($sentCount < count($targets)) {
        $_SESSION['message'] = ['type' => 'success', 'text' => "Email sent to {$sentCount} of " . count($targets) . " recipients."];
    } else {
        $_SESSION['message'] = ['type' => 'success', 'text' => "Email sent successfully to {$sentCount} recipient(s)."];
    }

    header("Location: custom_email.php");
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Custom Email</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); ?>">

    <link rel="preconnect" href="https://fonts.googleapis.com/">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&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/css/style.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.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">
                    <h1 class="h3 mb-2">Custom Email</h1>
                    <p class="text-muted mb-0">Send custom emails to one customer, all customers, or any external email.</p>
                </div>
            </div>

            <?php if (isset($_SESSION['message'])): $message = $_SESSION['message']; unset($_SESSION['message']); ?>
                <script>
                    document.addEventListener('DOMContentLoaded', function () {
                        Swal.fire({
                            icon: '<?= $message['type']; ?>',
                            title: '<?= $message['type'] === 'success' ? 'Done' : 'Error'; ?>',
                            text: '<?= htmlspecialchars($message['text'], ENT_QUOTES, 'UTF-8'); ?>',
                            confirmButtonText: 'OK'
                        });
                    });
                </script>
            <?php endif; ?>

            <div class="card shadow-sm">
                <div class="card-body p-4">
                    <form method="post">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label">Recipient Option</label>
                                <select name="recipient_mode" id="recipient_mode" class="form-select" required>
                                    <option value="single">One Customer</option>
                                    <option value="all">All Customers</option>
                                    <option value="manual">Manual Email(s)</option>
                                </select>
                            </div>

                            <div class="col-md-8" id="single_customer_wrap">
                                <label class="form-label">Select Customer</label>
                                <select name="customer_id" id="customer_id" class="form-select">
                                    <option value="">Choose customer</option>
                                    <?php foreach ($customers as $cust): ?>
                                        <option value="<?= (int) $cust['customerid']; ?>">
                                            <?= htmlspecialchars(trim(($cust['firstname'] ?? '') . ' ' . ($cust['lastname'] ?? ''))); ?> - <?= htmlspecialchars($cust['email'] ?? 'No Email'); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="col-12 d-none" id="manual_email_wrap">
                                <label class="form-label">Manual Email Address(es)</label>
                                <input type="text" name="manual_emails" id="manual_emails" class="form-control" placeholder="e.g john@mail.com, jane@mail.com">
                                <small class="text-muted">Use comma, semicolon, or space to separate multiple emails.</small>
                            </div>

                            <div class="col-12">
                                <label class="form-label">Email Subject</label>
                                <input type="text" name="subject" class="form-control" required>
                            </div>

                            <div class="col-12">
                                <label class="form-label">Email Message</label>
                                <textarea name="message" rows="8" class="form-control" required placeholder="Type your custom message here..."></textarea>
                            </div>

                            <div class="col-12">
                                <button type="submit" name="send_custom_email" class="btn btn-primary">
                                    <i class="bi bi-send-fill me-1"></i> Send Email
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</main>

<script src="assets/vendor/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script src="assets/js/functions.js"></script>
<script>
    (function () {
        const modeSelect = document.getElementById('recipient_mode');
        const singleWrap = document.getElementById('single_customer_wrap');
        const manualWrap = document.getElementById('manual_email_wrap');
        const customerSelect = document.getElementById('customer_id');
        const manualInput = document.getElementById('manual_emails');

        const syncRecipientFields = () => {
            const mode = modeSelect.value;
            if (mode === 'single') {
                singleWrap.classList.remove('d-none');
                manualWrap.classList.add('d-none');
                customerSelect.required = true;
                manualInput.required = false;
            } else if (mode === 'manual') {
                singleWrap.classList.add('d-none');
                manualWrap.classList.remove('d-none');
                customerSelect.required = false;
                manualInput.required = true;
            } else {
                singleWrap.classList.add('d-none');
                manualWrap.classList.add('d-none');
                customerSelect.required = false;
                manualInput.required = false;
            }
        };

        modeSelect.addEventListener('change', syncRecipientFields);
        syncRecipientFields();
    })();
</script>
</body>
</html>
