<?php
require_once './includes/session.php';
require_once './includes/message.php';
require_once './includes/utils.php';

$session = SessionManager::getInstance();
$messageObj = new Message();

// Handle delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if (!isset($_POST['csrf_token']) || !Utils::validateCSRFToken($_POST['csrf_token'])) {
        $errorMessage = 'Invalid request.';
    } else {
        if ($_POST['action'] === 'clean_all') {
            if ($messageObj->deleteAllMessages()) {
                $successMessage = "All messages deleted.";
            }
        } elseif ($_POST['action'] === 'delete' && isset($_POST['id'])) {
            if ($messageObj->deleteMessage((int)$_POST['id'])) {
                $successMessage = "Message deleted.";
            }
        } elseif ($_POST['action'] === 'bulk_delete' && isset($_POST['item_ids'])) {
            $ids = array_map('intval', $_POST['item_ids']);
            if ($messageObj->deleteMultipleMessages($ids)) {
                $successMessage = count($ids) . " messages deleted.";
            }
        }
    }
}

$search = isset($_GET['search']) ? Utils::sanitizeInput($_GET['search']) : '';
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$perPage = 20;
$filters = [];
if (!empty($search)) $filters['search'] = $search;

$totalRecords = $messageObj->getTotalCount($filters);
$totalPages = ceil($totalRecords / $perPage);
$messages = $messageObj->getMessages($page, $perPage, $filters, 'date', 'DESC');
$csrfToken = Utils::generateCSRFToken();

include_once './includes/header.php';
?>

<?php if (isset($successMessage)): ?>
    <div class="alert alert-success"><?php echo $successMessage; ?></div>
<?php endif; ?>
<?php if (isset($errorMessage)): ?>
    <div class="alert alert-danger"><?php echo $errorMessage; ?></div>
<?php endif; ?>

<!-- Search -->
<div class="search-bar">
    <form method="GET" style="display:flex;gap:8px;width:100%;">
        <input type="text" name="search" class="form-control" placeholder="Search messages..." value="<?php echo htmlspecialchars($search); ?>">
        <button type="submit" class="btn btn-primary btn-sm">Go</button>
        <?php if ($search): ?><a href="messages.php" class="btn btn-secondary btn-sm">✕</a><?php endif; ?>
    </form>
</div>

<!-- Count + Actions -->
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px;">
    <span style="font-size:12px;color:#64748B;font-weight:500;"><?php echo number_format($totalRecords); ?> messages</span>
    <form method="POST" onsubmit="return confirm('Delete ALL messages?')">
        <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
        <input type="hidden" name="action" value="clean_all">
        <button type="submit" class="btn btn-danger btn-sm">Delete All</button>
    </form>
</div>

<!-- Message Cards -->
<?php if (!empty($messages)): ?>
    <?php foreach ($messages as $msg): ?>
    <div class="data-item">
        <div class="item-header">
            <span class="item-id">#<?php echo $msg['id']; ?> · <?php echo htmlspecialchars($msg['type'] ?? 'sms'); ?></span>
            <span class="item-date"><?php echo Utils::formatDate($msg['date'], 'd M H:i'); ?></span>
        </div>
        <div class="item-title"><?php echo htmlspecialchars($msg['title']); ?></div>
        <div class="item-sub"><?php echo htmlspecialchars($msg['mobile']); ?></div>
        <div style="font-size:12px;color:#475569;margin-top:6px;line-height:1.4;word-break:break-word;"><?php echo htmlspecialchars(Utils::truncateString($msg['subheading'], 300)); ?></div>

        <div class="item-actions">
            <a href="view_message.php?id=<?php echo $msg['id']; ?>" class="btn btn-sm btn-outline-primary">View</a>
            <form method="POST" style="display:inline;" onsubmit="return confirm('Delete?')">
                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?php echo $msg['id']; ?>">
                <button type="submit" class="btn btn-sm btn-danger">Del</button>
            </form>
        </div>
    </div>
    <?php endforeach; ?>
<?php else: ?>
    <div style="text-align:center;padding:40px;color:#94A3B8;font-size:13px;">No messages found</div>
<?php endif; ?>

<!-- Pagination -->
<?php if ($totalPages > 1): ?>
<div style="margin-top:12px;">
    <?php
    $queryParams = $_GET;
    unset($queryParams['page']);
    $qs = http_build_query($queryParams);
    $url = '?' . $qs . (empty($qs) ? 'page=' : '&page=');
    echo Utils::generatePagination($page, $totalPages, $url);
    ?>
</div>
<?php endif; ?>

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