<?php
$pageTitle = 'Messages';
require_once dirname(__DIR__) . '/includes/header.php';

// Ensure table exists
db()->query("CREATE TABLE IF NOT EXISTS contact_messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    full_name VARCHAR(100),
    email VARCHAR(150),
    phone VARCHAR(30),
    subject VARCHAR(200),
    message TEXT,
    is_read TINYINT(1) DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

// Delete
if (isset($_GET['delete'])) {
    db()->query("DELETE FROM contact_messages WHERE id=".(int)$_GET['delete']);
    flash('Message deleted.','success');
    redirect(ADMIN_URL.'/pages/messages.php');
}

// View single
$viewing = null;
if (isset($_GET['view'])) {
    $mid = (int)$_GET['view'];
    $viewing = db()->query("SELECT * FROM contact_messages WHERE id=$mid")->fetch_assoc();
    if ($viewing) db()->query("UPDATE contact_messages SET is_read=1 WHERE id=$mid");
}

// Mark all read
if (isset($_GET['mark_all_read'])) {
    db()->query("UPDATE contact_messages SET is_read=1");
    flash('All messages marked as read.','success');
    redirect(ADMIN_URL.'/pages/messages.php');
}

// Filter
$filter = $_GET['filter'] ?? 'all'; // all | unread
$where = $filter === 'unread' ? "WHERE is_read=0" : "";
$messages = db()->query("SELECT * FROM contact_messages $where ORDER BY created_at DESC")->fetch_all(MYSQLI_ASSOC);
$unread = db()->query("SELECT COUNT(*) as c FROM contact_messages WHERE is_read=0")->fetch_assoc()['c'];
?>
<div class="page-header">
    <h1>Messages <?php if($unread>0): ?><span class="badge badge-red" style="font-size:13px;margin-left:4px"><?=$unread?> new</span><?php endif; ?></h1>
    <div class="page-header-actions" style="display:flex;gap:10px;align-items:center">
        <a href="?filter=all" class="btn <?=$filter==='all'?'btn-primary':'btn-secondary'?> btn-sm">All</a>
        <a href="?filter=unread" class="btn <?=$filter==='unread'?'btn-primary':'btn-secondary'?> btn-sm">Unread <?php if($unread>0): ?>(<?=$unread?>)<?php endif; ?></a>
        <?php if($unread>0): ?><a href="?mark_all_read=1" class="btn btn-secondary btn-sm"><i class="fas fa-check-double"></i> Mark All Read</a><?php endif; ?>
    </div>
</div>

<?php if ($viewing): ?>
<!-- Single message view -->
<div class="card" style="margin-bottom:20px">
    <div class="card-header">
        <i class="fas fa-envelope-open" style="color:var(--brand)"></i>
        <h2>Message from <?=e($viewing['full_name'])?></h2>
        <div class="card-actions">
            <a href="messages.php" class="btn btn-secondary btn-sm"><i class="fas fa-arrow-left"></i> Back</a>
            <button onclick="confirmDelete('messages.php?delete=<?=$viewing['id']?>','this message')" class="btn btn-danger btn-sm"><i class="fas fa-trash"></i> Delete</button>
        </div>
    </div>
    <div class="card-body">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:20px;padding:16px;background:#f9fafb;border-radius:8px">
            <div><span style="font-size:12px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em">From</span><div style="font-weight:600;margin-top:2px"><?=e($viewing['full_name'])?></div></div>
            <div><span style="font-size:12px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em">Email</span><div style="margin-top:2px"><a href="mailto:<?=e($viewing['email'])?>" style="color:var(--brand)"><?=e($viewing['email'])?></a></div></div>
            <?php if($viewing['phone']): ?><div><span style="font-size:12px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em">Phone</span><div style="margin-top:2px"><?=e($viewing['phone'])?></div></div><?php endif; ?>
            <div><span style="font-size:12px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em">Subject</span><div style="font-weight:600;margin-top:2px"><?=e($viewing['subject']??'No Subject')?></div></div>
            <div><span style="font-size:12px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em">Received</span><div style="margin-top:2px"><?=date('F j, Y \a\t g:i A', strtotime($viewing['created_at']))?></div></div>
        </div>
        <div style="background:#fff;border:1px solid var(--border);border-radius:8px;padding:20px;line-height:1.7;white-space:pre-wrap"><?=e($viewing['message']??'')?></div>
        <div style="margin-top:16px;display:flex;gap:10px">
            <a href="mailto:<?=e($viewing['email'])?>?subject=Re: <?=e(urlencode($viewing['subject']??'Your Inquiry'))?>" class="btn btn-primary"><i class="fas fa-reply"></i> Reply via Email</a>
            <?php if(!empty($viewing['phone'])): ?><a href="https://wa.me/<?=preg_replace('/\D/','',$viewing['phone'])?>" target="_blank" class="btn btn-secondary" style="color:#25d366"><i class="fab fa-whatsapp"></i> WhatsApp</a><?php endif; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Messages list -->
<div class="card">
    <div class="card-header">
        <i class="fas fa-inbox" style="color:var(--brand)"></i>
        <h2>Inbox</h2>
        <span style="color:var(--muted);font-size:13px;margin-left:auto"><?=count($messages)?> messages</span>
    </div>
    <div class="table-wrap">
        <?php if (empty($messages)): ?>
        <div style="padding:48px;text-align:center;color:var(--muted)">
            <i class="fas fa-inbox" style="font-size:36px;opacity:.3;display:block;margin-bottom:12px"></i>
            No messages <?=$filter==='unread'?'unread':''?> yet.
        </div>
        <?php else: ?>
        <table>
            <thead><tr><th></th><th>Name</th><th>Email</th><th>Subject</th><th>Date</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach ($messages as $m): ?>
            <tr style="<?=!$m['is_read']?'background:#fffbeb;font-weight:600':''?>">
                <td style="width:10px"><?=!$m['is_read']?'<span style="width:8px;height:8px;background:var(--brand);border-radius:50%;display:inline-block"></span>':''?></td>
                <td><?=e($m['full_name'])?></td>
                <td style="font-size:13px;color:var(--muted)"><?=e($m['email'])?></td>
                <td style="max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?=e($m['subject']??'—')?></td>
                <td style="white-space:nowrap;font-size:12px;color:var(--muted)"><?=date('M j, Y g:i A', strtotime($m['created_at']))?></td>
                <td>
                    <div style="display:flex;gap:6px">
                        <a href="messages.php?view=<?=$m['id']?>" class="btn btn-secondary btn-sm btn-icon" title="View"><i class="fas fa-eye"></i></a>
                        <a href="mailto:<?=e($m['email'])?>" class="btn btn-secondary btn-sm btn-icon" title="Reply"><i class="fas fa-reply"></i></a>
                        <button onclick="confirmDelete('messages.php?delete=<?=$m['id']?>','message from <?=e(addslashes($m['full_name']))?>')" class="btn btn-danger btn-sm btn-icon" title="Delete"><i class="fas fa-trash"></i></button>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>
    </div>
</div>
<?php require_once dirname(__DIR__) . '/includes/footer.php'; ?>
