<?php
// Check if the tracking table exists
$tableCheck = $con->query("SHOW TABLES LIKE 'email_tracking'");
if (!$tableCheck || $tableCheck->num_rows === 0): ?>
<div class="alert alert-warning d-flex align-items-center mb-3">
    <i class="fad fa-exclamation-triangle me-2"></i>
    <div>
        This feature is not available yet.
    </div>
</div>
<?php return; 
endif; 

$query = "SELECT * FROM email_tracking ORDER BY sent_at DESC LIMIT 250";
$result = $con->query($query);
?>
<div class="note note-warning mb-3">
    <strong>Email Tracking:</strong> Email are tracked using a tiny invisible image ("tracking pixel"). Tracking may not be 100% accurate, as some email clients block images or use privacy features.
</div>
<div class="row mb-3">
    <div class="col-md-6">
        <div class="input-group input-group-sm">
            <span class="input-group-text bg-info text-light"><i class="fad fa-search"></i></span>
            <input type="text" class="form-control" id="trackerSearch" placeholder="Search by recipient, type, subject...">
        </div>
    </div>
</div>
<div class="card mb-4">
    <div class="card-header d-flex align-items-center justify-content-between">
        <span><i class="fad fa-envelope-open-text me-2"></i>Tracked Emails</span>
        <span class="badge bg-secondary"><?= $result->num_rows ?> entries</span>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-sm table-striped align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th>Date Sent</th>
                        <th>Recipient</th>
                        <th>Type</th>
                        <th>Subject</th>
                        <th>Viewed</th>
                        <th>Opened At</th>
                        <th>Details</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($result->num_rows): ?>
                    <?php while ($row = $result->fetch_assoc()): ?>
                    <tr>
                        <td class="small"><?= date('d-m-Y H:i', strtotime($row['sent_at'])) ?></td>
                        <td><?= htmlspecialchars($row['recipient']) ?></td>
                        <td><span class="badge bg-info text-light"><?= htmlspecialchars(strtoupper($row['email_type'])) ?></span></td>
                        <td class="text-truncate" style="max-width: 280px;"><?= htmlspecialchars($row['subject']) ?></td>
                        <td>
                            <?php if ($row['opened']): ?>
                            <span class="badge bg-success"><i class="fad fa-eye"></i> Viewed</span>
                            <?php else: ?>
                            <span class="badge bg-secondary"><i class="fad fa-eye-slash"></i> Not Viewed</span>
                            <?php endif; ?>
                        </td>
                        <td class="small"><?= $row['opened_at'] ? date('d-m-Y H:i', strtotime($row['opened_at'])) : '-' ?></td>
                        <td>
                            <?php if ($row['opened']): ?>
                            <button class="btn btn-outline-info btn-sm"
                                    data-mdb-tooltip-init
                                    data-mdb-placement="top"
                                    title="View Info"
                                    onclick="showEmailInfoModal('<?= $row['id'] ?>', '<?= htmlspecialchars(addslashes($row['recipient'])) ?>', '<?= htmlspecialchars(addslashes($row['opened_ip'])) ?>', '<?= htmlspecialchars(addslashes($row['opened_ua'])) ?>')">
                                <i class="fad fa-info-circle"></i>
                            </button>
                            <?php else: ?>
                            <span class="text-muted small">-</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                    <?php else: ?>
                    <tr>
                        <td colspan="7" class="text-center text-muted">No emails found.</td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modal for email open info -->
<div class="modal fade" id="emailInfoModal" tabindex="-1" aria-labelledby="emailInfoModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="emailInfoModalLabel"><i class="fad fa-info-circle me-2"></i>Email View Details</h5>
                <button type="button" class="btn-close" data-mdb-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="emailInfoModalBody">
                <!-- Content loaded by JS -->
            </div>
        </div>
    </div>
</div>

<script>
function showEmailInfoModal(id, recipient, ip, ua) {
    let html = `
    <ul class="list-group list-group-flush">
      <li class="list-group-item"><strong>Recipient:</strong> ${recipient}</li>
      <li class="list-group-item"><strong>Opened IP:</strong> ${ip}</li>
      <li class="list-group-item"><strong>User Agent:</strong><br><code class="small">${ua}</code></li>
    </ul>
  `;
    document.getElementById('emailInfoModalBody').innerHTML = html;
    var modal = new mdb.Modal(document.getElementById('emailInfoModal'));
    modal.show();
}

function showEmailInfoModal(id, recipient, ip, ua) {
    let html = `
    <ul class="list-group list-group-flush">
      <li class="list-group-item"><strong>Recipient:</strong> ${recipient}</li>
      <li class="list-group-item"><strong>Opened IP:</strong> ${ip}</li>
      <li class="list-group-item"><strong>User Agent:</strong><br><code class="small">${ua}</code></li>
    </ul>
  `;
    document.getElementById('emailInfoModalBody').innerHTML = html;
    var modal = new mdb.Modal(document.getElementById('emailInfoModal'));
    modal.show();
}

// Live search for the tracker table
document.addEventListener('DOMContentLoaded', function() {
    const input = document.getElementById('trackerSearch');
    const table = document.querySelector('.table');
    input?.addEventListener('input', function() {
        const val = this.value.trim().toLowerCase();
        table.querySelectorAll('tbody tr').forEach(function(row) {
            const rowText = row.textContent.toLowerCase();
            row.style.display = rowText.indexOf(val) !== -1 ? '' : 'none';
        });
    });
});

document.getElementById('navBox').innerHTML = '<li class="breadcrumb-item">Tools <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadcrumb-item active">Email Tracking</li>';
</script>