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

// Fetch all active users for the dropdown
try {
    $stmt = $pdo->prepare("SELECT id, username, email, full_name FROM users WHERE status = 1 ORDER BY username ASC");
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $users = [];
}

// Fetch scheduled emails
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 = [];
}
?>
<title>Send Email - <?php echo $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>
    .email-form-card {
        border-left: 4px solid #4e73df;
        border-radius: 6px;
    }
    .select2-container--default .select2-selection--multiple {
        border: 1px solid #d1d3e2;
        border-radius: 0.35rem;
        min-height: 38px;
        padding: 3px 8px;
    }
    .select2-container--default .select2-selection--multiple .select2-selection__choice {
        background-color: #4e73df;
        border-color: #4e73df;
        color: #fff;
        border-radius: 3px;
        padding: 2px 8px;
    }
    .select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
        color: #fff;
        margin-right: 5px;
    }
    .recipient-toggle .btn, .send-toggle .btn {
        border-radius: 20px;
        padding: 6px 20px;
        font-size: 0.85rem;
        font-weight: 600;
    }
    .char-count {
        font-size: 0.75rem;
        color: #858796;
    }
    .email-preview {
        background: #f8f9fc;
        border: 1px solid #e3e6f0;
        border-radius: 6px;
        padding: 20px;
        max-height: 300px;
        overflow-y: auto;
    }
    .schedule-section {
        background: #f8f9fc;
        border: 1px solid #e3e6f0;
        border-radius: 8px;
        padding: 15px;
        margin-top: 10px;
    }
    .badge-scheduled { background: #f6c23e; color: #fff; }
    .badge-sent { background: #1cc88a; color: #fff; }
    .badge-failed { background: #e74a3b; color: #fff; }
    .badge-pending { background: #4e73df; color: #fff; }
</style>

<!-- Container Fluid -->
<div class="container-fluid" id="container-wrapper">
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Send Email</h1>
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard">Home</a></li>
            <li class="breadcrumb-item active" aria-current="page">Send Email</li>
        </ol>
    </div>

    <div class="row">
        <div class="col-lg-8">
            <div class="card email-form-card mb-4 shadow-sm">
                <div class="card-header py-3 d-flex align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-envelope mr-2"></i>Compose Email
                    </h6>
                </div>
                <div class="card-body">
                    <form id="sendEmailForm">
                        <!-- Recipient Type Toggle -->
                        <div class="form-group">
                            <label class="font-weight-bold">Send To</label>
                            <div class="recipient-toggle mb-3">
                                <div class="btn-group" role="group">
                                    <button type="button" class="btn btn-primary active" id="btnIndividual" onclick="toggleRecipient('individual')">
                                        <i class="fas fa-user mr-1"></i> Individual Users
                                    </button>
                                    <button type="button" class="btn btn-outline-primary" id="btnAll" onclick="toggleRecipient('all')">
                                        <i class="fas fa-users mr-1"></i> All Users
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Individual User Selection -->
                        <div class="form-group" id="individualSection">
                            <label class="font-weight-bold">Select Recipients</label>
                            <select class="form-control" id="userSelect" name="user_ids[]" multiple="multiple">
                                <?php foreach ($users as $user): ?>
                                    <option value="<?php echo $user['id']; ?>">
                                        <?php echo htmlspecialchars($user['username']); ?> (<?php echo htmlspecialchars($user['email']); ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <small class="text-muted">Search and select one or more users</small>
                        </div>

                        <!-- Hidden field for recipient type -->
                        <input type="hidden" name="recipient_type" id="recipientType" value="individual">

                        <!-- Subject -->
                        <div class="form-group">
                            <label class="font-weight-bold">Subject <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="subject" id="emailSubject" 
                                   placeholder="Enter email subject" required maxlength="255">
                            <small class="char-count"><span id="subjectCount">0</span>/255 characters</small>
                        </div>

                        <!-- Message Body -->
                        <div class="form-group">
                            <label class="font-weight-bold">Message Body <span class="text-danger">*</span></label>
                            <textarea class="form-control" name="message" id="emailMessage" rows="10" 
                                      placeholder="Enter your email message here..." required></textarea>
                            <small class="text-muted">You can use basic HTML tags for formatting (e.g., &lt;b&gt;, &lt;i&gt;, &lt;br&gt;, &lt;a&gt;)</small>
                        </div>

                        <!-- Send Type Toggle -->
                        <div class="form-group">
                            <label class="font-weight-bold">Delivery</label>
                            <div class="send-toggle mb-2">
                                <div class="btn-group" role="group">
                                    <button type="button" class="btn btn-success active" id="btnSendNow" onclick="toggleSendType('now')">
                                        <i class="fas fa-paper-plane mr-1"></i> Send Now
                                    </button>
                                    <button type="button" class="btn btn-outline-warning" id="btnSchedule" onclick="toggleSendType('schedule')">
                                        <i class="fas fa-clock mr-1"></i> Schedule
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Schedule Section (hidden by default) -->
                        <div class="schedule-section" id="scheduleSection" style="display:none;">
                            <div class="form-group mb-0">
                                <label class="font-weight-bold"><i class="fas fa-calendar-alt mr-1 text-warning"></i> Schedule Date & Time</label>
                                <input type="datetime-local" class="form-control" name="scheduled_at" id="scheduledAt">
                                <small class="text-muted">Email will be sent automatically at this time (server time)</small>
                            </div>
                        </div>

                        <input type="hidden" name="send_type" id="sendType" value="now">

                        <!-- Action Buttons -->
                        <div class="d-flex justify-content-between align-items-center mt-3">
                            <button type="button" class="btn btn-outline-secondary" onclick="previewEmail()">
                                <i class="fas fa-eye mr-1"></i> Preview
                            </button>
                            <div>
                                <button type="reset" class="btn btn-light mr-2">
                                    <i class="fas fa-undo mr-1"></i> Reset
                                </button>
                                <button type="submit" class="btn btn-primary" 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 shadow-sm mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-warning">
                        <i class="fas fa-clock mr-2"></i>Scheduled Emails
                    </h6>
                </div>
                <div class="card-body">
                    <?php if (empty($scheduled_emails)): ?>
                        <p class="text-muted text-center mb-0">No scheduled emails yet.</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-sm table-hover">
                                <thead class="thead-light">
                                    <tr>
                                        <th>Subject</th>
                                        <th>To</th>
                                        <th>Scheduled For</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($scheduled_emails as $se): ?>
                                    <tr>
                                        <td><strong><?php echo htmlspecialchars(substr($se['subject'], 0, 40)); ?></strong></td>
                                        <td>
                                            <?php if ($se['recipient_type'] === 'all'): ?>
                                                <span class="badge badge-info">All Users</span>
                                            <?php else: ?>
                                                <span class="badge badge-secondary">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-pending">Pending</span>
                                            <?php elseif ($se['status'] === 'sent'): ?>
                                                <span class="badge badge-sent">Sent (<?php echo $se['sent_count']; ?>)</span>
                                            <?php else: ?>
                                                <span class="badge badge-failed">Failed</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($se['status'] === 'pending'): ?>
                                                <button class="btn btn-sm btn-danger" 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>

        <!-- Sidebar Info -->
        <div class="col-lg-4">
            <div class="card shadow-sm mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-info">
                        <i class="fas fa-info-circle mr-2"></i>Email Info
                    </h6>
                </div>
                <div class="card-body">
                    <p class="mb-2"><strong>Total Users:</strong> <?php echo count($users); ?></p>
                    <p class="mb-2"><strong>From:</strong> <?php echo htmlspecialchars($site_data['web_email']); ?></p>
                    <p class="mb-2"><strong>Site Name:</strong> <?php echo htmlspecialchars($site_data['web_name']); ?></p>
                    <hr>
                    <p class="text-muted small mb-2">
                        <i class="fas fa-lightbulb text-warning mr-1"></i>
                        Emails are sent via SMTP using PHPMailer.
                    </p>
                    <p class="text-muted small mb-0">
                        <i class="fas fa-clock text-info mr-1"></i>
                        Scheduled emails are sent automatically by cron job.
                    </p>
                </div>
            </div>

            <!-- Preview Card -->
            <div class="card shadow-sm mb-4" id="previewCard" style="display:none;">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-success">
                        <i class="fas fa-eye mr-2"></i>Email Preview
                    </h6>
                </div>
                <div class="card-body">
                    <div class="email-preview" id="emailPreviewContent">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Scripts -->
<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>
$(document).ready(function() {
    $('#userSelect').select2({
        placeholder: 'Search users by name or email...',
        allowClear: true,
        width: '100%'
    });

    $('#emailSubject').on('input', function() {
        $('#subjectCount').text($(this).val().length);
    });

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

// Toggle recipient type
function toggleRecipient(type) {
    $('#recipientType').val(type);
    if (type === 'all') {
        $('#individualSection').slideUp(200);
        $('#btnAll').removeClass('btn-outline-primary').addClass('btn-primary active');
        $('#btnIndividual').removeClass('btn-primary active').addClass('btn-outline-primary');
    } else {
        $('#individualSection').slideDown(200);
        $('#btnIndividual').removeClass('btn-outline-primary').addClass('btn-primary active');
        $('#btnAll').removeClass('btn-primary active').addClass('btn-outline-primary');
    }
}

// Toggle send type (now vs schedule)
function toggleSendType(type) {
    $('#sendType').val(type);
    if (type === 'schedule') {
        $('#scheduleSection').slideDown(200);
        $('#btnSchedule').removeClass('btn-outline-warning').addClass('btn-warning active');
        $('#btnSendNow').removeClass('btn-success active').addClass('btn-outline-success');
        $('#sendBtn').html('<i class="fas fa-clock mr-1"></i> Schedule Email');
        $('#sendBtn').removeClass('btn-primary').addClass('btn-warning');
    } else {
        $('#scheduleSection').slideUp(200);
        $('#btnSendNow').removeClass('btn-outline-success').addClass('btn-success active');
        $('#btnSchedule').removeClass('btn-warning active').addClass('btn-outline-warning');
        $('#sendBtn').html('<i class="fas fa-paper-plane mr-1"></i> Send Email');
        $('#sendBtn').removeClass('btn-warning').addClass('btn-primary');
    }
}

// Preview email
function previewEmail() {
    var subject = $('#emailSubject').val();
    var message = $('#emailMessage').val();
    if (!subject && !message) {
        Swal.fire('Empty', 'Please enter a subject and message to preview.', 'info');
        return;
    }
    var previewHtml = '<p><strong>Subject:</strong> ' + $('<span>').text(subject).html() + '</p><hr>';
    previewHtml += '<div>' + message + '</div>';
    $('#emailPreviewContent').html(previewHtml);
    $('#previewCard').slideDown(200);
}

// Cancel scheduled email
function cancelScheduled(id) {
    Swal.fire({
        title: 'Cancel Scheduled Email?',
        text: 'This email will not be sent.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#e74a3b',
        cancelButtonColor: '#858796',
        confirmButtonText: 'Yes, Cancel It'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'ajax/schedule_email.php',
                type: 'POST',
                data: { action: 'cancel', email_id: id },
                dataType: 'json',
                success: function(data) {
                    if (data.status == '1') {
                        Swal.fire('Cancelled!', data.msg, 'success').then(() => location.reload());
                    } else {
                        Swal.fire('Error!', data.msg, 'error');
                    }
                }
            });
        }
    });
}

// Form submission
$('#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('Error', 'Please enter an email subject.', 'warning'); return; }
    if (!message) { Swal.fire('Error', 'Please enter an email message.', 'warning'); return; }
    if (recipientType === 'individual') {
        var selectedUsers = $('#userSelect').val();
        if (!selectedUsers || selectedUsers.length === 0) {
            Swal.fire('Error', 'Please select at least one recipient.', 'warning'); return;
        }
    }
    if (sendType === 'schedule') {
        var scheduledAt = $('#scheduledAt').val();
        if (!scheduledAt) {
            Swal.fire('Error', 'Please select a date and time for scheduling.', 'warning'); return;
        }
    }

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

    var confirmTitle = sendType === 'schedule' ? 'Schedule Email?' : 'Send Email?';
    var confirmBtn = sendType === 'schedule' 
        ? '<i class="fas fa-clock"></i> Yes, Schedule' 
        : '<i class="fas fa-paper-plane"></i> Yes, Send';
    var confirmHtml = sendType === 'schedule'
        ? 'Schedule email to <strong>' + recipientText + '</strong> for <strong>' + $('#scheduledAt').val().replace('T', ' at ') + '</strong>'
        : 'Send email to <strong>' + recipientText + '</strong> now?';

    Swal.fire({
        title: confirmTitle,
        html: confirmHtml + '<br><br>Subject: <strong>' + $('<span>').text(subject).html() + '</strong>',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: sendType === 'schedule' ? '#f6c23e' : '#4e73df',
        cancelButtonColor: '#858796',
        confirmButtonText: confirmBtn,
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            var ajaxUrl = sendType === 'schedule' ? 'ajax/schedule_email.php' : 'ajax/send_email.php';
            var loadingTitle = sendType === 'schedule' ? 'Scheduling...' : 'Sending...';

            Swal.fire({
                title: loadingTitle,
                allowOutsideClick: false,
                allowEscapeKey: false,
                didOpen: () => { Swal.showLoading(); }
            });

            var formData = $(this).serialize();
            if (sendType === 'schedule') {
                formData += '&action=schedule';
            }

            $.ajax({
                url: ajaxUrl,
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function(data) {
                    Swal.close();
                    if (data.status == '1') {
                        Swal.fire({
                            title: 'Success!',
                            html: data.msg,
                            icon: 'success',
                            confirmButtonColor: '#1cc88a'
                        }).then(() => {
                            if (sendType === 'schedule') location.reload();
                            else {
                                $('#sendEmailForm')[0].reset();
                                $('#userSelect').val(null).trigger('change');
                                $('#subjectCount').text('0');
                                $('#previewCard').slideUp(200);
                            }
                        });
                    } else {
                        Swal.fire('Error!', data.msg, 'error');
                    }
                },
                error: function(xhr) {
                    Swal.close();
                    Swal.fire('Error!', 'An error occurred. Please try again.', 'error');
                }
            });
        }
    });
});
</script>

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