<?php
$admin_title = "Pesan Masuk";
require_once 'includes/header.php';

$error = '';
$success = '';
$active_message = null;

// Handle Delete Request
if (isset($_GET['delete'])) {
    $del_id = intval($_GET['delete']);
    try {
        $stmt = $pdo->prepare("DELETE FROM messages WHERE id = ?");
        $stmt->execute([$del_id]);
        $success = "Pesan berhasil dihapus.";
    } catch (Exception $e) {
        $error = "Gagal menghapus pesan: " . $e->getMessage();
    }
}

// Handle Mark as Read
if (isset($_GET['id'])) {
    $msg_id = intval($_GET['id']);
    try {
        // Fetch message details
        $stmt = $pdo->prepare("SELECT * FROM messages WHERE id = ?");
        $stmt->execute([$msg_id]);
        $active_message = $stmt->fetch();
        
        if ($active_message) {
            // Update as read if it was unread
            if ($active_message['is_read'] == 0) {
                $stmt = $pdo->prepare("UPDATE messages SET is_read = 1 WHERE id = ?");
                $stmt->execute([$msg_id]);
            }
        }
    } catch (Exception $e) {
        $error = "Terjadi kesalahan: " . $e->getMessage();
    }
}

// Fetch all messages
try {
    $stmt = $pdo->prepare("SELECT * FROM messages ORDER BY id DESC");
    $stmt->execute();
    $messages = $stmt->fetchAll();
} catch (Exception $e) {
    $messages = [];
}
?>

<?php if (!empty($error)): ?>
    <div style="background-color: rgba(239, 68, 68, 0.15); border: 1px solid var(--error); color: #f87171; padding: 12px 15px; border-radius: 6px; font-size: 13px; margin-bottom: 20px;">
        <i class="fas fa-exclamation-circle" style="margin-right: 5px;"></i> <?php echo $error; ?>
    </div>
<?php endif; ?>

<?php if (!empty($success)): ?>
    <div style="background-color: rgba(16, 185, 129, 0.15); border: 1px solid var(--success); color: #34d399; padding: 12px 15px; border-radius: 6px; font-size: 13px; margin-bottom: 20px;">
        <i class="fas fa-check-circle" style="margin-right: 5px;"></i> <?php echo $success; ?>
    </div>
<?php endif; ?>

<!-- Detail Viewer if ID is set -->
<?php if ($active_message): ?>
    <div class="form-card" style="margin-bottom: 40px; border-color: var(--primary);">
        <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 20px; border-bottom: 1px solid var(--border-color); padding-bottom: 15px;">
            <div>
                <h2 style="font-size: 18px; font-weight: 700; color: var(--secondary);"><?php echo htmlspecialchars($active_message['subject']); ?></h2>
                <p style="font-size: 13px; color: var(--text-muted); margin-top: 5px;">
                    Dari: <strong><?php echo htmlspecialchars($active_message['name']); ?></strong> 
                    (&lt;<?php echo htmlspecialchars($active_message['email']); ?>&gt;) | 
                    HP: <strong><?php echo htmlspecialchars($active_message['phone']); ?></strong>
                </p>
            </div>
            <div style="text-align: right;">
                <span style="font-size: 12px; color: var(--text-muted); display: block;"><?php echo date('d F Y, H:i', strtotime($active_message['created_at'])); ?></span>
                <a href="messages.php" style="font-size: 13px; color: var(--primary); font-weight: 600; text-decoration: none; display: inline-block; margin-top: 8px;"><i class="fas fa-times"></i> Tutup Detail</a>
            </div>
        </div>
        
        <div style="font-size: 15px; line-height: 1.8; color: var(--text-dark); background-color: var(--bg-light); padding: 25px; border-radius: 8px; border: 1px solid var(--border-color); white-space: pre-wrap; margin-bottom: 20px;">
            <?php echo htmlspecialchars($active_message['message']); ?>
        </div>
        
        <div style="display: flex; gap: 15px;">
            <!-- WhatsApp Reply Link if phone exists -->
            <?php if (!empty($active_message['phone'])): ?>
                <?php 
                $reply_number = str_replace(['+', ' ', '-'], '', $active_message['phone']);
                if (substr($reply_number, 0, 1) === '0') {
                    $reply_number = '62' . substr($reply_number, 1);
                }
                ?>
                <a href="https://wa.me/<?php echo $reply_number; ?>?text=Halo%20<?php echo urlencode($active_message['name']); ?>%2C%20terima%20kasih%20telah%20menghubungi%20PT%20Namora%20Nexa%20Niaga..." 
                   class="btn-submit" style="text-decoration: none; display: inline-flex; align-items: center; gap: 8px;" target="_blank" rel="noopener noreferrer">
                    <i class="fab fa-whatsapp"></i> Balas via WhatsApp
                </a>
            <?php endif; ?>
            
            <a href="mailto:<?php echo $active_message['email']; ?>?subject=Re: <?php echo urlencode($active_message['subject']); ?>" 
               class="btn-cancel" style="display: inline-flex; align-items: center; gap: 8px;">
                <i class="fas fa-envelope"></i> Balas via Email
            </a>
            
            <a href="messages.php?delete=<?php echo $active_message['id']; ?>" 
               class="btn-cancel" style="color: var(--error); border-color: rgba(239, 68, 68, 0.2); background: rgba(239, 68, 68, 0.05);"
               onclick="return confirm('Apakah Anda yakin ingin menghapus pesan ini?');">
                <i class="fas fa-trash"></i> Hapus Pesan
            </a>
        </div>
    </div>
<?php endif; ?>

<!-- Message List Table -->
<div class="data-card">
    <div class="data-card-header">
        <h2>Daftar Pesan Masuk</h2>
    </div>
    
    <div class="table-responsive">
        <table class="admin-table">
            <thead>
                <tr>
                    <th>Pengirim</th>
                    <th>Subjek</th>
                    <th>No. HP</th>
                    <th>Tanggal</th>
                    <th>Status</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (count($messages) > 0): ?>
                    <?php foreach ($messages as $msg): ?>
                        <tr style="<?php echo ($msg['is_read'] == 0) ? 'background-color: rgba(197, 168, 128, 0.03); font-weight: 600;' : ''; ?>">
                            <td>
                                <strong><?php echo htmlspecialchars($msg['name']); ?></strong><br>
                                <span style="font-size: 11px; color: var(--text-muted);"><?php echo htmlspecialchars($msg['email']); ?></span>
                            </td>
                            <td><?php echo htmlspecialchars($msg['subject']); ?></td>
                            <td><?php echo htmlspecialchars($msg['phone']); ?></td>
                            <td><?php echo date('d M Y, H:i', strtotime($msg['created_at'])); ?></td>
                            <td>
                                <?php if ($msg['is_read'] == 1): ?>
                                    <span class="badge badge-success" style="background: rgba(16, 185, 129, 0.1); color: var(--success); font-weight: 500;">Dibaca</span>
                                <?php else: ?>
                                    <span class="badge badge-warning" style="font-weight: 700;">Baru</span>
                                <?php endif; ?>
                            </td>
                            <td class="action-btns">
                                <a href="messages.php?id=<?php echo $msg['id']; ?>" class="btn-action view" title="Buka Pesan"><i class="fas fa-eye"></i></a>
                                <a href="messages.php?delete=<?php echo $msg['id']; ?>" class="btn-action delete" title="Hapus" onclick="return confirm('Apakah Anda yakin ingin menghapus pesan ini?');"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="6" style="text-align: center; color: var(--text-muted); padding: 30px;">Belum ada pesan masuk.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php require_once 'includes/footer.php'; ?>
