<?php require 'sidebar.php'; ?>

<style>
.stat-cards-row {
    display: flex;
    gap: 15px;
    margin-bottom: 20px;
    flex-wrap: wrap;
}

.stat-card-mini {
    flex: 1;
    min-width: 200px;
    background: white;
    padding: 15px;
    border-radius: 6px;
    box-shadow: 0 1px 4px rgba(0,0,0,0.1);
    border-left: 3px solid #ed174f;
}

.stat-card-mini.new { border-left-color: #2196F3; }
.stat-card-mini.read { border-left-color: #FF9800; }
.stat-card-mini.replied { border-left-color: #4CAF50; }

.stat-number-mini {
    font-size: 24px;
    font-weight: 700;
    color: #1a1a1a;
    margin-bottom: 3px;
}

.stat-label-mini {
    font-size: 11px;
    color: #666;
    text-transform: uppercase;
}

.badge-new {
    background: #2196F3;
    color: white;
    padding: 3px 8px;
    border-radius: 10px;
    font-size: 10px;
    font-weight: 600;
}

.badge-read {
    background: #FF9800;
    color: white;
    padding: 3px 8px;
    border-radius: 10px;
    font-size: 10px;
    font-weight: 600;
}

.badge-replied {
    background: #4CAF50;
    color: white;
    padding: 3px 8px;
    border-radius: 10px;
    font-size: 10px;
    font-weight: 600;
}

.btn-action-sm {
    padding: 4px 8px;
    border: none;
    border-radius: 3px;
    font-size: 11px;
    cursor: pointer;
    margin-right: 2px;
    color: white;
}

.btn-view { background: #2196F3; }
.btn-view:hover { background: #1976D2; }
.btn-mark-read { background: #FF9800; }
.btn-mark-read:hover { background: #F57C00; }
.btn-mark-replied { background: #4CAF50; }
.btn-mark-replied:hover { background: #388E3C; }
.btn-delete { background: #f44336; }
.btn-delete:hover { background: #d32f2f; }

.modal-overlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    z-index: 9999;
}

.modal-content {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: white;
    border-radius: 8px;
    padding: 20px;
    max-width: 600px;
    width: 90%;
    max-height: 80vh;
    overflow-y: auto;
    box-shadow: 0 10px 40px rgba(0,0,0,0.2);
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 2px solid #f0f0f0;
}

.modal-title {
    font-size: 18px;
    font-weight: 700;
    color: #1a1a1a;
}

.modal-close {
    background: none;
    border: none;
    font-size: 24px;
    color: #999;
    cursor: pointer;
}

.modal-close:hover {
    color: #ed174f;
}

.message-detail {
    margin-bottom: 12px;
}

.message-detail-label {
    font-size: 10px;
    font-weight: 600;
    color: #666;
    text-transform: uppercase;
    margin-bottom: 3px;
}

.message-detail-value {
    font-size: 13px;
    color: #333;
    padding: 8px;
    background: #f8f9fa;
    border-radius: 4px;
}

.message-text {
    white-space: pre-wrap;
    line-height: 1.5;
}
</style>

<!--Page Container-->
<section class="page-container">
  <div class="page-content-wrapper">

    <!--Main Content-->
    <div class="content sm-gutter">
      <div class="container-fluid padding-25 sm-padding-10">

        <div class="section-title">
          <h5 class="text-truncate">Contact Messages</h5>
        </div>

        <!-- Statistics Cards -->
        <div class="stat-cards-row">
            <div class="stat-card-mini">
                <div class="stat-number-mini"><?php echo $stats['total']; ?></div>
                <div class="stat-label-mini">Total Messages</div>
            </div>
            <div class="stat-card-mini new">
                <div class="stat-number-mini"><?php echo $stats['new']; ?></div>
                <div class="stat-label-mini">New Messages</div>
            </div>
            <div class="stat-card-mini read">
                <div class="stat-number-mini"><?php echo $stats['read']; ?></div>
                <div class="stat-label-mini">Read Messages</div>
            </div>
            <div class="stat-card-mini replied">
                <div class="stat-number-mini"><?php echo $stats['replied']; ?></div>
                <div class="stat-label-mini">Replied</div>
            </div>
        </div>

        <div class="row">
          <div class="col-12 c-col-12">
            
            <?php if (empty($messages)): ?>
                <div class="alert alert-info text-center" style="padding: 30px; margin-top: 20px;">
                    <i class="dripicons-inbox" style="font-size: 40px; color: #2196F3; margin-bottom: 10px;"></i>
                    <h5>No Messages Yet</h5>
                    <p style="margin: 0;">Contact messages will appear here when users submit the contact form.</p>
                </div>
            <?php else: ?>

            <div class="card card-data-tables">
              <div class="card-body">
                <div class="table-responsive">
                  <table id="contactTable" class="table table-striped" style="width:100%">
                    <thead>
                      <tr>
                        <th style="width: 4%;">ID</th>
                        <th style="width: 15%;">Name</th>
                        <th style="width: 18%;">Email</th>
                        <th style="width: 20%;">Subject</th>
                        <th style="width: 12%;">Date</th>
                        <th style="width: 8%;" class="text-center">Status</th>
                        <th style="width: 23%;" class="text-center">Actions</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php foreach ($messages as $msg): ?>
                      <tr>
                        <td><?php echo $msg['contact_id']; ?></td>
                        <td><?php echo htmlspecialchars($msg['contact_name']); ?></td>
                        <td><?php echo htmlspecialchars($msg['contact_email']); ?></td>
                        <td><?php echo htmlspecialchars(substr($msg['contact_subject'], 0, 35)) . (strlen($msg['contact_subject']) > 35 ? '...' : ''); ?></td>
                        <td><?php echo date('M d, Y', strtotime($msg['contact_date'])); ?></td>
                        <td class="text-center">
                          <span class="badge-<?php echo $msg['contact_status']; ?>">
                            <?php echo ucfirst($msg['contact_status']); ?>
                          </span>
                        </td>
                        <td class="text-center">
                          <button class="btn-action-sm btn-view" onclick='viewMessage(<?php echo json_encode($msg); ?>)' title="View">
                            <i class="dripicons-preview"></i>
                          </button>
                          <?php if ($msg['contact_status'] !== 'read'): ?>
                          <button class="btn-action-sm btn-mark-read" onclick="updateStatus(<?php echo $msg['contact_id']; ?>, 'read')" title="Mark as Read">
                            <i class="dripicons-checkmark"></i>
                          </button>
                          <?php endif; ?>
                          <?php if ($msg['contact_status'] !== 'replied'): ?>
                          <button class="btn-action-sm btn-mark-replied" onclick="updateStatus(<?php echo $msg['contact_id']; ?>, 'replied')" title="Mark as Replied">
                            <i class="dripicons-mail"></i>
                          </button>
                          <?php endif; ?>
                          <button class="btn-action-sm btn-delete" onclick="deleteMessage(<?php echo $msg['contact_id']; ?>)" title="Delete">
                            <i class="dripicons-trash"></i>
                          </button>
                        </td>
                      </tr>
                      <?php endforeach; ?>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>

            <?php endif; ?>

          </div>
        </div>

      </div>
    </div>
    <!--End Main Content-->

  </div>
</section>
<!--End Page Container-->

<!-- Message Detail Modal -->
<div id="messageModal" class="modal-overlay" onclick="closeModal(event)">
    <div class="modal-content" onclick="event.stopPropagation()">
        <div class="modal-header">
            <h2 class="modal-title">Message Details</h2>
            <button class="modal-close" onclick="closeModal()">&times;</button>
        </div>
        <div id="modalBody"></div>
    </div>
</div>

<script>
<?php if (!empty($messages)): ?>
$(document).ready(function() {
    $('#contactTable').DataTable({
        order: [[0, 'desc']],
        pageLength: 10,
        responsive: true
    });
});
<?php endif; ?>

function viewMessage(msg) {
    const modalBody = document.getElementById('modalBody');
    modalBody.innerHTML = `
        <div class="message-detail">
            <div class="message-detail-label">From</div>
            <div class="message-detail-value">${msg.contact_name}</div>
        </div>
        <div class="message-detail">
            <div class="message-detail-label">Email</div>
            <div class="message-detail-value">
                <a href="mailto:${msg.contact_email}">${msg.contact_email}</a>
            </div>
        </div>
        <div class="message-detail">
            <div class="message-detail-label">Subject</div>
            <div class="message-detail-value">${msg.contact_subject}</div>
        </div>
        <div class="message-detail">
            <div class="message-detail-label">Message</div>
            <div class="message-detail-value message-text">${msg.contact_message}</div>
        </div>
        <div class="message-detail">
            <div class="message-detail-label">Date</div>
            <div class="message-detail-value">${new Date(msg.contact_date).toLocaleString()}</div>
        </div>
        <div class="message-detail">
            <div class="message-detail-label">IP Address</div>
            <div class="message-detail-value">${msg.contact_ip || 'N/A'}</div>
        </div>
    `;
    document.getElementById('messageModal').style.display = 'block';
    
    if (msg.contact_status === 'new') {
        updateStatus(msg.contact_id, 'read', false);
    }
}

function closeModal(event) {
    if (!event || event.target.id === 'messageModal') {
        document.getElementById('messageModal').style.display = 'none';
    }
}

function updateStatus(id, status, reload = true) {
    fetch('../controller/update_contact_status.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `contact_id=${id}&status=${status}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success && reload) {
            location.reload();
        }
    })
    .catch(error => console.error('Error:', error));
}

function deleteMessage(id) {
    if (!confirm('Are you sure you want to delete this message?')) {
        return;
    }
    
    fetch('../controller/delete_contact.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `contact_id=${id}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('Failed to delete message');
        }
    })
    .catch(error => console.error('Error:', error));
}
</script>
