<?php
session_name('super_admin_session');
if (!is_dir(dirname(__DIR__) . '/session_data/super')) {
    mkdir(dirname(__DIR__) . '/session_data/super', 0700, true);
}
session_save_path(dirname(__DIR__) . '/session_data/super');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();
error_reporting(0);
include('includes/dbconnection.php');
require_once 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName    = $stResult['term_name'];

$emailContent = null;
$emailId = isset($_GET['email_id']) ? intval($_GET['email_id']) : 0;

if ($emailId > 0) {
    $stmt = $dbh->prepare("SELECT sender, subject, body, DATE_FORMAT(timestamp, '%Y-%m-%d %H:%i') AS date_received FROM emails WHERE id = ?");
    $stmt->execute([$emailId]);
    $emailContent = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($emailContent) {
        // Mark as read
        $updateStmt = $dbh->prepare("UPDATE emails SET read_status = 1 WHERE id = ?");
        $updateStmt->execute([$emailId]);
    }
}

function getEnvEmails()
{
    $envPath = __DIR__ . '/.env';
    if (!file_exists($envPath))
        return [];
    $lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $data = [];
    foreach ($lines as $line) {
        if (strpos($line, '=') && strpos(trim($line), '#') !== 0) {
            [$k, $v] = explode('=', $line, 2);
            $data[trim($k)] = trim($v, '" ');
        }
    }
    $accounts = [];
    foreach ($data as $key => $val) {
        if (str_ends_with($key, '_EMAIL')) {
            $prefix = str_replace('_EMAIL', '', $key);
            $accounts[$val] = ucfirst(strtolower(str_replace('_', ' ', $prefix)));
        }
    }
    return $accounts;
}

$accounts = getEnvEmails();

function decodeEmailBody($body)
{
    // Try base64 decode, and check if it's valid base64
    $base64Decoded = base64_decode($body, true);
    if ($base64Decoded !== false && strlen($base64Decoded) > 0 && preg_match('/[a-zA-Z0-9]/', $base64Decoded)) {
        return nl2br(htmlspecialchars($base64Decoded));
    }
    // Try quoted-printable decode
    $qpDecoded = quoted_printable_decode($body);
    if (strlen($qpDecoded) > 0 && preg_match('/[a-zA-Z0-9]/', $qpDecoded)) {
        return nl2br(htmlspecialchars($qpDecoded));
    }
    // Otherwise treat as plain text
    return nl2br(htmlspecialchars($body));
}



?>
<!DOCTYPE html>
<html lang="en">
<?php @include("includes/head.php"); ?>
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">

<body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <?php @include("includes/header.php"); ?>
        <?php @include("includes/sidebar.php"); ?>
        <div class="content-wrapper">
            <section class="content-header premium-header">
                <div class="container-fluid">
                    <div class="header-glass-card">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <div class="title-section">
                                    <div class="icon-box bg-primary-gradient shadow-sm">
                                        <i class="fas fa-envelope"></i>
                                    </div>
                                    <div>
                                        <h1 class="premium-title text-primary">
                                            Email Management
                                            <span class="premium-subtitle text-secondary">Manage Emails</span>
                                        </h1>
                            <div class="mt-1">
                              <?php if ($currentSessionName): ?>
                                <span class="badge badge-primary mr-1">
                                  <i class="fas fa-calendar-alt"></i>
                                  <?= htmlspecialchars($currentSessionName) ?>
                                </span>
                              <?php endif; ?>
                              <?php if ($currentTermName): ?>
                                <span class="badge badge-success">
                                  <i class="fas fa-bookmark"></i>
                                  <?= htmlspecialchars($currentTermName) ?>
                                </span>
                              <?php else: ?>
                                <span class="badge badge-warning">
                                  <i class="fas fa-exclamation-triangle"></i> No active term
                                </span>
                              <?php endif; ?>
                            </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <nav aria-label="breadcrumb">
                                    <ol class="breadcrumb premium-breadcrumb">
                                        <li class="breadcrumb-item"><a href="dashboard.php"
                                                class="text-primary">Home</a></li>
                                        <li class="breadcrumb-item active" aria-current="page">Email Management</li>
                                    </ol>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
            </section>



            <section class="content">
                <div class="container-fluid">
                    <div class="card card-primary">
                        <div class="card-header">
                            <h5 class="card-title font-weight-bold"><i class="fas fa-envelope"></i> Email Management
                            </h5>
                        </div>

                        <div class="card-body">
                            <select id="emailDropdown" class="form-control mb-3">
                                <option value="">-- Select Account --</option>
                                <?php foreach ($accounts as $email => $label): ?>
                                        <option value="<?= htmlspecialchars($email) ?>">
                                            <?= htmlspecialchars("$label ($email)") ?>
                                        </option>
                                <?php endforeach; ?>
                            </select>
                            <!-- Place email content section here -->
                            <div id="emailContentSection" style="<?= $emailContent ? '' : 'display:none;' ?>">
                                <?php if ($emailContent): ?>
                                        <div class="card mb-4">
                                            <div class="card-header bg-info text-white">
                                                <h5><?= htmlspecialchars($emailContent['subject']) ?></h5>
                                            </div>
                                            <div class="card-body">
                                                <p><strong>From:</strong> <?= htmlspecialchars($emailContent['sender']) ?></p>
                                                <p><small><em>Received:
                                                            <?= htmlspecialchars($emailContent['timestamp']) ?></em></small></p>
                                                <hr>
                                                <div><?= $emailContent['body'] ?></div>
                                            </div>
                                        </div>
                                <?php elseif ($emailId > 0): ?>
                                        <div class="alert alert-warning">Email not found.</div>
                                <?php endif; ?>
                            </div>



                            <ul class="nav nav-tabs">
                                <li class="nav-item"><a class="nav-link active" id="inbox-tab" data-toggle="tab"
                                        href="#inboxSection">Inbox</a></li>
                                <li class="nav-item"><a class="nav-link" id="outbox-tab" data-toggle="tab"
                                        href="#outboxSection">Outbox</a></li>
                            </ul>

                            <div class="tab-content mt-3">
                                <div class="tab-pane fade show active" id="inboxSection">
                                    <table id="inboxTable" class="table table-bordered table-hover">
                                        <thead class="table-primary">
                                            <tr>
                                                <th>From</th>
                                                <th>Subject</th>
                                                <th>Date</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody></tbody>
                                    </table>
                                </div>
                                <div class="tab-pane fade" id="outboxSection">
                                    <table id="outboxTable" class="table table-bordered table-hover">
                                        <thead class="table-primary">
                                            <tr>
                                                <th>To</th>
                                                <th>Subject</th>
                                                <th>Date</th>
                                                <th>View</th>
                                            </tr>
                                        </thead>
                                        <tbody></tbody>
                                    </table>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>

        <!-- View Message Modal -->
        <div class="modal fade" id="viewMessageModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Message</h5>
                    </div>
                    <div class="modal-body" id="messageBody"></div>
                    <div class="modal-footer"><button class="btn btn-secondary" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Reply Modal -->
        <div class="modal fade" id="replyModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <form id="replyForm" method="POST" action="send_reply.php">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">Reply Email</h5>
                        </div>
                        <div class="modal-body">
                            <input type="hidden" name="from_account" id="fromAccount">
                            <div class="mb-3"><label>To:</label><input type="email" class="form-control" id="replyTo"
                                    name="to" readonly></div>
                            <div class="mb-3"><label>Subject:</label><input type="text" class="form-control"
                                    id="replySubject" name="subject"></div>
                            <div class="mb-3"><label>Message:</label>
                                <div id="quillEditor" style="height:200px;"></div>
                                <input type="hidden" name="message" id="quillContent">
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="submit" class="btn btn-primary" id="sendReplyBtn">Send</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <?php @include("includes/footer.php"); ?>
    </div>

    <?php @include("includes/foot.php"); ?>
    <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>

    <script>
        let quill;
        $(document).ready(function () {
            quill = new Quill('#quillEditor', { theme: 'snow' });

            // Inbox pagination links
            $(document).on('click', '.ajax-page-link', function (e) {
                e.preventDefault();
                const email = $(this).data('email');
                const page = $(this).data('page');
                if (!email || !page) return;
                $('#inboxTable tbody').html('<tr><td colspan="4">Loading...</td></tr>');
                $.post('fetch_email.php', { email: email, page: page }, function (data) {
                    $('#inboxTable tbody').html(data);
                });
            });

            // Outbox pagination links
            $(document).on('click', '.ajax-page-link', function (e) {
                e.preventDefault();
                const email = $(this).data('email');
                const page = $(this).data('page');
                if (!email || !page) return;
                $('#outboxTable tbody').html('<tr><td colspan="4">Loading...</td></tr>');
                $.post('fetch_outbox.php', { email: email, page: page }, function (data) {
                    $('#outboxTable tbody').html(data);
                });
            });

            // Email dropdown change loads page 1 inbox
            $('#emailDropdown').on('change', function () {
                $('#emailContentSection').hide();
                const email = $(this).val();
                if (!email) return;
                $('#inboxTable tbody').html('<tr><td colspan="4">Loading...</td></tr>');
                $.post('fetch_email.php', { email: email, page: 1 }, function (data) {
                    $('#inboxTable tbody').html(data);
                });
            });

            // Outbox tab click loads outbox
            $('#outbox-tab').on('click', function () {
                $('#emailContentSection').hide();
                const email = $('#emailDropdown').val();
                if (!email) return;
                $('#outboxTable tbody').html('<tr><td colspan="4">Loading...</td></tr>');
                $.post('fetch_outbox.php', { email }, function (data) {
                    $('#outboxTable tbody').html(data);
                });
            });

            // View message modal show
            $(document).on('click', '.view-message', function () {
                $('#messageBody').html($(this).data('body'));
                $('#viewMessageModal').modal('show');
            });

            // Reply modal show
            $(document).on('click', '.reply-btn', function () {
                $('#replyTo').val($(this).data('to'));
                $('#replySubject').val('Re: ' + $(this).data('subject'));
                $('#fromAccount').val($('#emailDropdown').val());
                quill.root.innerHTML = '';
                $('#replyModal').modal('show');
            });

            // Reply form — AJAX submit
            $('#replyForm').on('submit', function (e) {
                e.preventDefault();
                $('#quillContent').val(quill.root.innerHTML);

                const $btn = $('#sendReplyBtn');
                $btn.prop('disabled', true).text('Sending...');

                $.ajax({
                    url: 'send_reply.php',
                    method: 'POST',
                    data: $(this).serialize(),
                    dataType: 'json',
                    success: function (res) {
                        $('#replyModal').modal('hide');
                        if (res.success) {
                            Swal.fire({ icon: 'success', title: 'Sent!', text: res.msg, confirmButtonColor: '#3b82f6' });
                        } else {
                            Swal.fire({ icon: 'error', title: 'Error', text: res.msg, confirmButtonColor: '#3b82f6' });
                        }
                    },
                    error: function (xhr) {
                        $('#replyModal').modal('hide');
                        Swal.fire({ icon: 'error', title: 'Error', text: 'Request failed: ' + xhr.status, confirmButtonColor: '#3b82f6' });
                    },
                    complete: function () {
                        $btn.prop('disabled', false).text('Send');
                    }
                });
            });
        });


    </script>

</body>

</html>