<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include('include/header.php');
$page_title = WEB_NAME . " | Send Email";

try {
    $stmt = $pdo->query("SELECT id, username, email, full_name FROM users WHERE status = 1 ORDER BY username ASC");
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $users = []; }

try {
    $sched_stmt = $pdo->query("SELECT se.*, u.username as created_by_name FROM scheduled_emails se LEFT JOIN users u ON se.created_by = u.id ORDER BY se.created_at DESC LIMIT 20");
    $scheduled_emails = $sched_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $scheduled_emails = []; }

$smtp = get_mail_settings($pdo, $site_data);
$smtp_ok = !empty($smtp['smtp_host']) && !empty($smtp['smtp_username']) && !empty($smtp['smtp_password']);
?>
<title>Send Email - <?php echo htmlspecialchars($site_data['web_name']); ?></title>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
<style>
:root { --brand:#4e73df; --brand-dark:#224abe; --success:#1cc88a; --warning:#f6c23e; --danger:#e74a3b; }

/* ── Layout ── */
#container-wrapper { padding-bottom: 40px; }
.compose-wrap { display:grid; grid-template-columns:1fr 380px; gap:24px; align-items:start; }
@media(max-width:991px){ .compose-wrap{ grid-template-columns:1fr; } }

/* ── Compose card ── */
.compose-card { border-radius:14px; border:none; box-shadow:0 2px 16px rgba(0,0,0,.07); overflow:hidden; }
.compose-card .card-header {
    background:linear-gradient(135deg,#1a1a2e,#0f3460);
    padding:18px 24px;
    border:none;
}
.compose-card .card-header h6 { color:#fff; font-size:15px; font-weight:700; margin:0; }
.compose-card .card-header small { color:rgba(255,255,255,.55); font-size:12px; }
.compose-card .card-body { padding:28px 24px; }

/* ── Toggle pills ── */
.pill-group { display:flex; gap:8px; flex-wrap:wrap; }
.pill-btn {
    padding:7px 20px; border-radius:50px; font-size:13px; font-weight:600;
    border:2px solid #e3e6f0; background:#fff; color:#6c757d; cursor:pointer;
    transition:all .2s;
}
.pill-btn.active-blue  { background:var(--brand); border-color:var(--brand); color:#fff; }
.pill-btn.active-green { background:var(--success); border-color:var(--success); color:#fff; }
.pill-btn.active-warn  { background:var(--warning); border-color:var(--warning); color:#fff; }

/* ── Form fields ── */
.form-label { font-size:13px; font-weight:700; color:#374151; margin-bottom:6px; }
.form-control, .select2-container--default .select2-selection--multiple {
    border:1.5px solid #e3e6f0 !important; border-radius:10px !important;
    font-size:14px; transition:border-color .2s;
}
.form-control:focus { border-color:var(--brand) !important; box-shadow:0 0 0 3px rgba(78,115,223,.12) !important; }
textarea.form-control { resize:vertical; min-height:180px; }

.select2-container--default .select2-selection--multiple { min-height:42px !important; padding:4px 8px !important; }
.select2-container--default .select2-selection--multiple .select2-selection__choice {
    background:var(--brand) !important; border-color:var(--brand) !important;
    color:#fff !important; border-radius:20px !important; padding:2px 10px !important; font-size:12px;
}
.select2-container--default .select2-selection--multiple .select2-selection__choice__remove { color:rgba(255,255,255,.8) !important; }

/* ── Schedule box ── */
.schedule-box {
    background:#fffbeb; border:1.5px dashed var(--warning);
    border-radius:10px; padding:16px 18px; margin-top:4px;
}

/* ── Action bar ── */
.action-bar { display:flex; justify-content:space-between; align-items:center; margin-top:20px; flex-wrap:wrap; gap:10px; }
.btn-send { padding:10px 28px; border-radius:50px; font-size:14px; font-weight:700; }

/* ── Sidebar ── */
.side-card { border-radius:14px; border:none; box-shadow:0 2px 16px rgba(0,0,0,.07); margin-bottom:20px; overflow:hidden; }
.side-card .card-header { padding:14px 20px; border:none; }
.side-card .card-body { padding:18px 20px; }

/* ── SMTP status badge ── */
.smtp-badge {
    display:inline-flex; align-items:center; gap:6px;
    padding:5px 14px; border-radius:50px; font-size:12px; font-weight:700;
}
.smtp-ok   { background:#d1fae5; color:#065f46; }
.smtp-fail { background:#fee2e2; color:#991b1b; }
.smtp-dot  { width:8px; height:8px; border-radius:50%; display:inline-block; }
.smtp-ok .smtp-dot   { background:#10b981; }
.smtp-fail .smtp-dot { background:#ef4444; }

/* ── Preview iframe ── */
#previewFrame {
    width:100%; border:none; border-radius:10px;
    background:#f1f5f9; min-height:300px;
    transition:height .3s;
}

/* ── Scheduled table ── */
.sched-table th { font-size:12px; font-weight:700; color:#6b7280; text-transform:uppercase; letter-spacing:.5px; }
.sched-table td { font-size:13px; vertical-align:middle; }
.badge-pill-sm { padding:4px 10px; border-radius:50px; font-size:11px; font-weight:700; }

/* ── Tip box ── */
.tip-box { background:#f0f4ff; border-left:3px solid var(--brand); border-radius:0 8px 8px 0; padding:10px 14px; font-size:12px; color:#374151; }
</style>

<div class="container-fluid" id="container-wrapper">
    <!-- Breadcrumb -->
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h4 mb-0 font-weight-bold text-gray-800">
            <i class="fas fa-envelope-open-text mr-2 text-primary"></i>Send Email
        </h1>
        <ol class="breadcrumb mb-0">
            <li class="breadcrumb-item"><a href="dashboard">Home</a></li>
            <li class="breadcrumb-item active">Send Email</li>
        </ol>
    </div>

    <?php if (!$smtp_ok): ?>
    <div class="alert alert-danger border-0 rounded-lg mb-4" style="background:#fee2e2;">
        <i class="fas fa-exclamation-triangle mr-2"></i>
        <strong>SMTP not configured.</strong> Go to <a href="manage-settings.php" class="alert-link">Admin → Settings</a> and fill in your SMTP credentials before sending emails.
    </div>
    <?php endif; ?>

    <div class="compose-wrap">

        <!-- ══ LEFT: Compose ══ -->
        <div>
            <div class="card compose-card mb-4">
                <div class="card-header d-flex align-items-center justify-content-between">
                    <div>
                        <h6><i class="fas fa-pen-nib mr-2"></i>Compose Email</h6>
                        <small><?php echo count($users); ?> active users available</small>
                    </div>
                    <span class="smtp-badge <?php echo $smtp_ok ? 'smtp-ok' : 'smtp-fail'; ?>">
                        <span class="smtp-dot"></span>
                        SMTP <?php echo $smtp_ok ? 'Ready' : 'Not Set'; ?>
                    </span>
                </div>
                <div class="card-body">
                    <form id="sendEmailForm">
                        <input type="hidden" name="recipient_type" id="recipientType" value="individual">
                        <input type="hidden" name="send_type" id="sendType" value="now">

                        <!-- Send To -->
                        <div class="form-group">
                            <label class="form-label">Send To</label>
                            <div class="pill-group">
                                <button type="button" class="pill-btn active-blue" id="btnIndividual" onclick="toggleRecipient('individual')">
                                    <i class="fas fa-user mr-1"></i> Individual Users
                                </button>
                                <button type="button" class="pill-btn" id="btnAll" onclick="toggleRecipient('all')">
                                    <i class="fas fa-users mr-1"></i> All Users
                                    <span class="badge badge-light ml-1"><?php echo count($users); ?></span>
                                </button>
                            </div>
                        </div>

                        <!-- User selector -->
                        <div class="form-group" id="individualSection">
                            <label class="form-label">Select Recipients <span class="text-danger">*</span></label>
                            <select class="form-control" id="userSelect" name="user_ids[]" multiple>
                                <?php foreach ($users as $u): ?>
                                <option value="<?php echo $u['id']; ?>">
                                    <?php echo htmlspecialchars($u['username']); ?> — <?php echo htmlspecialchars($u['email']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                            <small class="text-muted">Type to search users</small>
                        </div>

                        <!-- Subject -->
                        <div class="form-group">
                            <label class="form-label">Subject <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="subject" id="emailSubject"
                                   placeholder="e.g. Important update from <?php echo htmlspecialchars($site_data['web_name']); ?>"
                                   maxlength="255" required>
                        </div>

                        <!-- Message -->
                        <div class="form-group">
                            <label class="form-label">
                                Message Body <span class="text-danger">*</span>
                                <span class="text-muted font-weight-normal ml-2" style="font-size:11px;">HTML supported · use <code>{{name}}</code> for personalisation</span>
                            </label>
                            <textarea class="form-control" name="message" id="emailMessage"
                                      placeholder="Write your message here..." required></textarea>
                        </div>

                        <!-- Delivery -->
                        <div class="form-group mb-1">
                            <label class="form-label">Delivery</label>
                            <div class="pill-group">
                                <button type="button" class="pill-btn active-green" id="btnNow" onclick="toggleSend('now')">
                                    <i class="fas fa-paper-plane mr-1"></i> Send Now
                                </button>
                                <button type="button" class="pill-btn" id="btnSchedule" onclick="toggleSend('schedule')">
                                    <i class="fas fa-clock mr-1"></i> Schedule
                                </button>
                            </div>
                        </div>

                        <!-- Schedule picker -->
                        <div class="schedule-box" id="scheduleBox" style="display:none;">
                            <label class="form-label"><i class="fas fa-calendar-alt mr-1 text-warning"></i> Pick Date & Time</label>
                            <input type="datetime-local" class="form-control" name="scheduled_at" id="scheduledAt">
                            <small class="text-muted">Server timezone. Cron job will dispatch at this time.</small>
                        </div>

                        <!-- Actions -->
                        <div class="action-bar">
                            <button type="button" class="btn btn-outline-secondary btn-sm rounded-pill px-4" onclick="livePreview()">
                                <i class="fas fa-eye mr-1"></i> Preview
                            </button>
                            <div class="d-flex gap-2">
                                <button type="reset" class="btn btn-light btn-sm rounded-pill px-4 mr-2" onclick="clearForm()">
                                    <i class="fas fa-undo mr-1"></i> Clear
                                </button>
                                <button type="submit" class="btn btn-primary btn-send" id="sendBtn">
                                    <i class="fas fa-paper-plane mr-1"></i> Send Email
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Scheduled emails table -->
            <div class="card side-card">
                <div class="card-header" style="background:#fffbeb;border-bottom:1px solid #fde68a;">
                    <h6 class="m-0 font-weight-bold" style="color:#92400e;">
                        <i class="fas fa-clock mr-2"></i>Scheduled Emails
                    </h6>
                </div>
                <div class="card-body p-0">
                    <?php if (empty($scheduled_emails)): ?>
                        <p class="text-muted text-center py-4 mb-0">No scheduled emails yet.</p>
                    <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover mb-0 sched-table">
                            <thead class="thead-light">
                                <tr>
                                    <th class="pl-4">Subject</th>
                                    <th>To</th>
                                    <th>Scheduled</th>
                                    <th>Status</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($scheduled_emails as $se): ?>
                            <tr>
                                <td class="pl-4"><strong><?php echo htmlspecialchars(mb_substr($se['subject'], 0, 35)); ?><?php echo strlen($se['subject']) > 35 ? '…' : ''; ?></strong></td>
                                <td>
                                    <?php if ($se['recipient_type'] === 'all'): ?>
                                        <span class="badge badge-pill-sm" style="background:#dbeafe;color:#1e40af;">All Users</span>
                                    <?php else: ?>
                                        <span class="badge badge-pill-sm" style="background:#f3f4f6;color:#374151;">Selected</span>
                                    <?php endif; ?>
                                </td>
                                <td><small><?php echo date('M d, Y h:i A', strtotime($se['scheduled_at'])); ?></small></td>
                                <td>
                                    <?php if ($se['status'] === 'pending'): ?>
                                        <span class="badge badge-pill-sm" style="background:#fef3c7;color:#92400e;">Pending</span>
                                    <?php elseif ($se['status'] === 'sent'): ?>
                                        <span class="badge badge-pill-sm" style="background:#d1fae5;color:#065f46;">Sent (<?php echo $se['sent_count']; ?>)</span>
                                    <?php else: ?>
                                        <span class="badge badge-pill-sm" style="background:#fee2e2;color:#991b1b;">Failed</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($se['status'] === 'pending'): ?>
                                    <button class="btn btn-sm btn-danger rounded-pill px-3" onclick="cancelScheduled(<?php echo $se['id']; ?>)">
                                        <i class="fas fa-times"></i>
                                    </button>
                                    <?php else: ?>
                                    <small class="text-muted"><?php echo $se['sent_at'] ? date('M d h:i A', strtotime($se['sent_at'])) : '—'; ?></small>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- ══ RIGHT: Sidebar ══ -->
        <div>
            <!-- Info card -->
            <div class="card side-card">
                <div class="card-header" style="background:linear-gradient(135deg,#1a1a2e,#0f3460);border:none;">
                    <h6 class="m-0 font-weight-bold text-white"><i class="fas fa-info-circle mr-2"></i>Email Info</h6>
                </div>
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="text-muted" style="font-size:13px;">Total Users</span>
                        <strong><?php echo count($users); ?></strong>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="text-muted" style="font-size:13px;">From Name</span>
                        <strong style="font-size:13px;"><?php echo htmlspecialchars($smtp['smtp_from_name'] ?: $site_data['web_name']); ?></strong>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <span class="text-muted" style="font-size:13px;">From Email</span>
                        <strong style="font-size:12px;"><?php echo htmlspecialchars($smtp['smtp_from_email'] ?: $site_data['web_email']); ?></strong>
                    </div>
                    <hr class="my-2">
                    <div class="tip-box mt-3">
                        <i class="fas fa-lightbulb text-warning mr-1"></i>
                        Use <code>{{name}}</code> in your message to personalise with each user's name.
                    </div>
                    <div class="tip-box mt-2">
                        <i class="fas fa-code text-primary mr-1"></i>
                        HTML tags like <code>&lt;b&gt;</code>, <code>&lt;a&gt;</code>, <code>&lt;br&gt;</code> are supported.
                    </div>
                    <?php if (!$smtp_ok): ?>
                    <a href="manage-settings.php" class="btn btn-danger btn-block mt-3 rounded-pill" style="font-size:13px;">
                        <i class="fas fa-cog mr-1"></i> Configure SMTP
                    </a>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Live preview card -->
            <div class="card side-card" id="previewCard" style="display:none;">
                <div class="card-header" style="background:#f0fdf4;border-bottom:1px solid #bbf7d0;">
                    <h6 class="m-0 font-weight-bold" style="color:#065f46;">
                        <i class="fas fa-eye mr-2"></i>Live Preview
                        <button type="button" class="close ml-auto" onclick="$('#previewCard').slideUp()" style="font-size:16px;">&times;</button>
                    </h6>
                </div>
                <div class="card-body p-2">
                    <iframe id="previewFrame" scrolling="no"></iframe>
                </div>
            </div>
        </div>

    </div><!-- /.compose-wrap -->
</div>

<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(function () {
    $('#userSelect').select2({ placeholder: 'Search users…', allowClear: true, width: '100%' });

    // Set min datetime
    var now = new Date();
    now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
    $('#scheduledAt').attr('min', now.toISOString().slice(0, 16));

    // Auto-preview on typing
    var previewTimer;
    $('#emailSubject, #emailMessage').on('input', function () {
        clearTimeout(previewTimer);
        previewTimer = setTimeout(function () {
            if ($('#previewCard').is(':visible')) livePreview();
        }, 600);
    });
});

function toggleRecipient(type) {
    $('#recipientType').val(type);
    if (type === 'all') {
        $('#individualSection').slideUp(200);
        $('#btnAll').addClass('active-blue').removeClass('active-green');
        $('#btnIndividual').removeClass('active-blue active-green');
    } else {
        $('#individualSection').slideDown(200);
        $('#btnIndividual').addClass('active-blue').removeClass('active-green');
        $('#btnAll').removeClass('active-blue active-green');
    }
}

function toggleSend(type) {
    $('#sendType').val(type);
    if (type === 'schedule') {
        $('#scheduleBox').slideDown(200);
        $('#btnSchedule').addClass('active-warn').removeClass('active-green active-blue');
        $('#btnNow').removeClass('active-green active-blue active-warn');
        $('#sendBtn').html('<i class="fas fa-clock mr-1"></i> Schedule Email')
                     .removeClass('btn-primary').addClass('btn-warning');
    } else {
        $('#scheduleBox').slideUp(200);
        $('#btnNow').addClass('active-green').removeClass('active-warn active-blue');
        $('#btnSchedule').removeClass('active-green active-warn active-blue');
        $('#sendBtn').html('<i class="fas fa-paper-plane mr-1"></i> Send Email')
                     .removeClass('btn-warning').addClass('btn-primary');
    }
}

function livePreview() {
    var subj = $('#emailSubject').val() || '(No subject)';
    var body = $('#emailMessage').val() || '<em style="color:#9ca3af">Your message will appear here…</em>';
    var html = `<!DOCTYPE html><html><head><meta charset="UTF-8">
    <style>body{margin:0;padding:16px;font-family:'Segoe UI',Arial,sans-serif;background:#f1f5f9;font-size:14px;color:#374151;}
    .wrap{background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 2px 12px rgba(0,0,0,.08);}
    .hdr{background:linear-gradient(135deg,#1a1a2e,#0f3460);padding:20px;text-align:center;color:#fff;}
    .hdr h2{margin:0;font-size:16px;} .subj{background:#e8f0fe;padding:10px 20px;font-weight:700;font-size:14px;}
    .bdy{padding:20px;line-height:1.7;} .ftr{background:#1a1a2e;padding:14px;text-align:center;color:rgba(255,255,255,.4);font-size:11px;}
    </style></head><body>
    <div class="wrap">
      <div class="hdr"><h2><?php echo htmlspecialchars($site_data['web_name']); ?></h2></div>
      <div class="subj">📧 ` + $('<span>').text(subj).html() + `</div>
      <div class="bdy">` + body + `</div>
      <div class="ftr">&copy; <?php echo date('Y'); ?> <?php echo htmlspecialchars($site_data['web_name']); ?></div>
    </div></body></html>`;

    var frame = document.getElementById('previewFrame');
    frame.srcdoc = html;
    frame.onload = function () {
        frame.style.height = (frame.contentDocument.body.scrollHeight + 20) + 'px';
    };
    $('#previewCard').slideDown(200);
}

function clearForm() {
    $('#sendEmailForm')[0].reset();
    $('#userSelect').val(null).trigger('change');
    $('#previewCard').slideUp(200);
    toggleRecipient('individual');
    toggleSend('now');
}

function cancelScheduled(id) {
    Swal.fire({
        title: 'Cancel this email?',
        text: 'It will be removed from the queue.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#e74a3b',
        cancelButtonColor: '#6b7280',
        confirmButtonText: 'Yes, cancel it'
    }).then(r => {
        if (!r.isConfirmed) return;
        $.post('ajax/schedule_email.php', { action: 'cancel', email_id: id }, function (d) {
            if (d.status == '1') Swal.fire('Cancelled', d.msg, 'success').then(() => location.reload());
            else Swal.fire('Error', d.msg, 'error');
        }, 'json');
    });
}

$('#sendEmailForm').on('submit', function (e) {
    e.preventDefault();

    var sendType      = $('#sendType').val();
    var recipientType = $('#recipientType').val();
    var subject       = $('#emailSubject').val().trim();
    var message       = $('#emailMessage').val().trim();

    if (!subject) { Swal.fire('Missing', 'Please enter a subject.', 'warning'); return; }
    if (!message) { Swal.fire('Missing', 'Please enter a message.', 'warning'); return; }

    if (recipientType === 'individual' && (!$('#userSelect').val() || !$('#userSelect').val().length)) {
        Swal.fire('Missing', 'Please select at least one recipient.', 'warning'); return;
    }
    if (sendType === 'schedule' && !$('#scheduledAt').val()) {
        Swal.fire('Missing', 'Please pick a schedule date & time.', 'warning'); return;
    }

    var toText = recipientType === 'all'
        ? 'ALL <?php echo count($users); ?> users'
        : $('#userSelect').val().length + ' user(s)';

    var isSchedule = sendType === 'schedule';
    var confirmHtml = isSchedule
        ? 'Schedule to <strong>' + toText + '</strong> at <strong>' + $('#scheduledAt').val().replace('T', ' ') + '</strong>'
        : 'Send now to <strong>' + toText + '</strong>';

    Swal.fire({
        title: isSchedule ? 'Schedule Email?' : 'Send Email?',
        html: confirmHtml + '<br><small class="text-muted">Subject: ' + $('<span>').text(subject).html() + '</small>',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: isSchedule ? '#f6c23e' : '#4e73df',
        cancelButtonColor: '#6b7280',
        confirmButtonText: isSchedule ? '&#128336; Schedule' : '&#9993; Send Now'
    }).then(r => {
        if (!r.isConfirmed) return;

        var url      = isSchedule ? 'ajax/schedule_email.php' : 'ajax/send_email.php';
        var formData = $('#sendEmailForm').serialize();
        if (isSchedule) formData += '&action=schedule';

        Swal.fire({ title: isSchedule ? 'Scheduling…' : 'Sending…', allowOutsideClick: false, didOpen: () => Swal.showLoading() });

        $.ajax({
            url: url, type: 'POST', data: formData, dataType: 'json',
            success: function (d) {
                Swal.close();
                if (d.status == '1') {
                    Swal.fire({ title: 'Done!', html: d.msg, icon: 'success', confirmButtonColor: '#1cc88a' })
                        .then(() => { if (isSchedule) location.reload(); else clearForm(); });
                } else {
                    Swal.fire('Failed', d.msg, 'error');
                }
            },
            error: function () {
                Swal.close();
                Swal.fire('Error', 'Request failed. Please try again.', 'error');
            }
        });
    });
});
</script>

<?php include('include/footer.php'); ?>
