<?php
/**
 * Admin - Contact Messages (pagination, delete)
 * PHP User Registration - https://rskworld.in
 * Developer: Molla Samser | RSK World
 * Contact: help@rskworld.in | +91 93305 39277
 * Year: 2026
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../includes/functions.php';

requireAdmin();
$baseHref = '..';

$pdo = getDbConnection();
$messages = [];
$total = 0;
$totalPages = 1;
$page = 1;
$perPage = 10;
$search = trim($_GET['q'] ?? '');

// Export CSV
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="messages-' . date('Y-m-d') . '.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['ID', 'Name', 'Email', 'Subject', 'Message', 'Date']);
    try {
        $sql = 'SELECT id, name, email, subject, message, created_at FROM contact_messages WHERE 1=1';
        $params = [];
        if ($search !== '') {
            $sql .= ' AND (name LIKE ? OR email LIKE ? OR subject LIKE ? OR message LIKE ?)';
            $p = '%' . $search . '%';
            $params = [$p, $p, $p, $p];
        }
        $sql .= ' ORDER BY created_at DESC';
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            fputcsv($out, [
                $row['id'] ?? '',
                $row['name'] ?? '',
                $row['email'] ?? '',
                $row['subject'] ?? '',
                $row['message'] ?? '',
                $row['created_at'] ?? ''
            ]);
        }
    } catch (PDOException $e) {}
    fclose($out);
    exit;
}

// Delete message
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
    $id = (int) $_POST['delete_id'];
    if ($id > 0) {
        try {
            $pdo->prepare('DELETE FROM contact_messages WHERE id = ?')->execute([$id]);
            setFlash('success', 'Message deleted.');
        } catch (PDOException $e) { /* table may not exist */ }
        header('Location: messages.php' . ($search !== '' ? '?q=' . urlencode($search) : ''));
        exit;
    }
}

try {
    $where = '1=1';
    $params = [];
    if ($search !== '') {
        $where .= ' AND (name LIKE ? OR email LIKE ? OR subject LIKE ? OR message LIKE ?)';
        $p = '%' . $search . '%';
        $params = [$p, $p, $p, $p];
    }
    $countSql = "SELECT COUNT(*) FROM contact_messages WHERE $where";
    $countStmt = $pdo->prepare($countSql);
    $countStmt->execute($params);
    $total = (int) $countStmt->fetchColumn();
    $totalPages = max(1, (int) ceil($total / $perPage));
    $page = max(1, min((int) ($_GET['page'] ?? 1), $totalPages));
    $offset = ($page - 1) * $perPage;
    $stmt = $pdo->prepare("SELECT id, name, email, subject, message, created_at FROM contact_messages WHERE $where ORDER BY created_at DESC LIMIT " . (int) $perPage . " OFFSET " . (int) $offset);
    $stmt->execute($params);
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // table may not exist
}

$success = getFlash('success');

$pageTitle = 'Admin - Messages';
require_once __DIR__ . '/../includes/header.php';
?>

<div class="page-content admin-content">
    <h1><i class="fas fa-inbox"></i> Contact Messages</h1>
    <p class="subtitle">PHP User Registration — <a href="https://rskworld.in" target="_blank">rskworld.in</a></p>

    <?php if ($success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <div class="admin-toolbar">
        <form method="get" action="messages.php" class="search-form">
            <input type="search" name="q" value="<?= htmlspecialchars($search) ?>" placeholder="Search name, email, subject, message">
            <button type="submit" class="btn btn-secondary btn-sm">Search</button>
        </form>
        <a href="messages.php?export=csv<?= $search !== '' ? '&q=' . urlencode($search) : '' ?>" class="btn btn-secondary btn-sm"><i class="fas fa-download"></i> Export CSV</a>
    </div>

    <?php if (empty($messages)): ?>
        <p>No messages yet.</p>
    <?php else: ?>
        <div class="table-wrap">
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Subject</th>
                        <th>Date</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($messages as $m): ?>
                    <tr>
                        <td><?= (int) $m['id'] ?></td>
                        <td><?= htmlspecialchars($m['name']) ?></td>
                        <td><a href="mailto:<?= htmlspecialchars($m['email']) ?>"><?= htmlspecialchars($m['email']) ?></a></td>
                        <td><?= htmlspecialchars($m['subject']) ?></td>
                        <td><?= date('M j, Y g:i A', strtotime($m['created_at'])) ?></td>
                        <td>
                            <form method="post" style="display:inline;" onsubmit="return confirm('Delete this message?');">
                                <input type="hidden" name="delete_id" value="<?= (int) $m['id'] ?>">
                                <button type="submit" class="btn-link text-danger">Delete</button>
                            </form>
                        </td>
                    </tr>
                    <tr class="message-row">
                        <td colspan="6"><strong>Message:</strong> <?= nl2br(htmlspecialchars($m['message'])) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <?php if ($totalPages > 1): ?>
        <div class="pagination">
            <?php $msgPagQs = $search !== '' ? '&q=' . urlencode($search) : ''; ?>
        <?php if ($page > 1): ?>
                <a href="messages.php?page=<?= $page - 1 . $msgPagQs ?>">« Previous</a>
            <?php endif; ?>
            <span class="pagination-info">Page <?= $page ?> of <?= $totalPages ?> (<?= $total ?> messages)</span>
            <?php if ($page < $totalPages): ?>
                <a href="messages.php?page=<?= $page + 1 . $msgPagQs ?>">Next »</a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    <?php endif; ?>
    <p><a href="index.php" class="btn btn-secondary">Back to Admin</a></p>
</div>

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