<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/layout.php';

$extra_head = '<link rel="stylesheet" href="/admin/assets/css/contact.css">';

require_once __DIR__ . '/includes/header.php';

$status = trim($_GET['status'] ?? '');
$search = trim($_GET['search'] ?? '');

$allowedStatuses = ['new', 'read', 'responded', 'archived'];

$where = [];
$params = [];

if ($status !== '' && in_array($status, $allowedStatuses, true)) {
    $where[] = 'status = :status';
    $params[':status'] = $status;
}

if ($search !== '') {
    $where[] = '
        (
            name LIKE :search 
            OR email LIKE :search 
            OR company LIKE :search 
            OR enquiry_type LIKE :search
            OR subject LIKE :search 
            OR message LIKE :search
        )
    ';
    $params[':search'] = '%' . $search . '%';
}

$whereSql = '';

if (!empty($where)) {
    $whereSql = 'WHERE ' . implode(' AND ', $where);
}

try {
    $stmt = $pdo->prepare("
        SELECT 
            id,
            name,
            email,
            company,
            enquiry_type,
            subject,
            status,
            created_at
        FROM contact_enquiries
        $whereSql
        ORDER BY created_at DESC
    ");

    $stmt->execute($params);
    $enquiries = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $countStmt = $pdo->query("
        SELECT 
            status,
            COUNT(*) AS total
        FROM contact_enquiries
        GROUP BY status
    ");

    $statusCountsRaw = $countStmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    $enquiries = [];
    $statusCountsRaw = [];
    $pageError = 'Unable to load contact enquiries.';
}

$statusCounts = [
    'new' => 0,
    'read' => 0,
    'responded' => 0,
    'archived' => 0
];

foreach ($statusCountsRaw as $row) {
    if (isset($statusCounts[$row['status']])) {
        $statusCounts[$row['status']] = (int)$row['total'];
    }
}

$totalCount = array_sum($statusCounts);

function statusBadgeClass(string $status): string
{
    return match ($status) {
        'new' => 'badge-new',
        'read' => 'badge-read',
        'responded' => 'badge-responded',
        'archived' => 'badge-archived',
        default => 'badge-read'
    };
}
?>

<div class="admin-page-header">
    <div>
        <h2>Contact Enquiries</h2>
        <p>View and manage messages submitted through the ThrillSense contact form.</p>
    </div>
</div>

<?php if (!empty($pageError)): ?>
    <div class="admin-message error">
        <?php echo htmlspecialchars($pageError, ENT_QUOTES, 'UTF-8'); ?>
    </div>
<?php endif; ?>

<div class="contact-stats">
    <div class="contact-stat-card">
        <span>Total</span>
        <strong><?php echo (int)$totalCount; ?></strong>
    </div>

    <div class="contact-stat-card">
        <span>New</span>
        <strong><?php echo (int)$statusCounts['new']; ?></strong>
    </div>

    <div class="contact-stat-card">
        <span>Read</span>
        <strong><?php echo (int)$statusCounts['read']; ?></strong>
    </div>

    <div class="contact-stat-card">
        <span>Responded</span>
        <strong><?php echo (int)$statusCounts['responded']; ?></strong>
    </div>

    <div class="contact-stat-card">
        <span>Archived</span>
        <strong><?php echo (int)$statusCounts['archived']; ?></strong>
    </div>
</div>

<div class="contact-filters">
    <form method="get" action="contact-enquiries.php">
        <div>
            <label for="search">Search</label>
            <input
                type="text"
                id="search"
                name="search"
                value="<?php echo htmlspecialchars($search, ENT_QUOTES, 'UTF-8'); ?>"
                placeholder="Search name, email, subject or message"
            >
        </div>

        <div>
            <label for="status">Status</label>
            <select id="status" name="status">
                <option value="">All statuses</option>
                <?php foreach ($allowedStatuses as $allowedStatus): ?>
                    <option
                        value="<?php echo htmlspecialchars($allowedStatus, ENT_QUOTES, 'UTF-8'); ?>"
                        <?php echo $status === $allowedStatus ? 'selected' : ''; ?>
                    >
                        <?php echo ucfirst($allowedStatus); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div>
            <button type="submit" class="btn btn-sm btn-primary">Filter</button>
        </div>
    </form>
</div>

<div class="admin-table-card">
    <?php if (empty($enquiries)): ?>
        <div class="empty-state">
            No contact enquiries found.
        </div>
    <?php else: ?>
        <table class="admin-table">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>From</th>
                    <th>Type</th>
                    <th>Subject</th>
                    <th>Status</th>
                    <th style="width: 120px;">Action</th>
                </tr>
            </thead>

            <tbody>
                <?php foreach ($enquiries as $enquiry): ?>
                    <tr>
                        <td>
                            <?php echo htmlspecialchars(date('d M Y', strtotime($enquiry['created_at'])), ENT_QUOTES, 'UTF-8'); ?>
                            <small><?php echo htmlspecialchars(date('H:i', strtotime($enquiry['created_at'])), ENT_QUOTES, 'UTF-8'); ?></small>
                        </td>

                        <td>
                            <strong><?php echo htmlspecialchars($enquiry['name'], ENT_QUOTES, 'UTF-8'); ?></strong>
                            <small><?php echo htmlspecialchars($enquiry['email'], ENT_QUOTES, 'UTF-8'); ?></small>

                            <?php if (!empty($enquiry['company'])): ?>
                                <small><?php echo htmlspecialchars($enquiry['company'], ENT_QUOTES, 'UTF-8'); ?></small>
                            <?php endif; ?>
                        </td>

                        <td>
                            <?php echo htmlspecialchars($enquiry['enquiry_type'], ENT_QUOTES, 'UTF-8'); ?>
                        </td>

                        <td>
                            <?php echo htmlspecialchars($enquiry['subject'], ENT_QUOTES, 'UTF-8'); ?>
                        </td>

                        <td>
                            <span class="status-badge <?php echo htmlspecialchars(statusBadgeClass($enquiry['status']), ENT_QUOTES, 'UTF-8'); ?>">
                                <?php echo htmlspecialchars($enquiry['status'], ENT_QUOTES, 'UTF-8'); ?>
                            </span>
                        </td>

                        <td>
                            <a class="admin-btn admin-btn-secondary" href="contact-enquiry.php?id=<?php echo (int)$enquiry['id']; ?>">
                                View
                            </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

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