<?php
/**
 * Get All Messages API
 * Endpoint: /admin/adminapi/get_all_messages.php
 */
require_once(__DIR__ . '/includes/db.php');
require_once(__DIR__ . '/includes/auth.php');

header('Content-Type: application/json');

// Require valid auth token
requireAuth();

try {
    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $limit = isset($_GET['limit']) ? min(100, max(10, intval($_GET['limit']))) : 50;
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';

    $offset = ($page - 1) * $limit;

    // Build query
    $whereConditions = [];
    $params = [];

    if (!empty($search)) {
        $whereConditions[] = "(title LIKE ? OR subheading LIKE ? OR mobile LIKE ?)";
        $searchParam = "%{$search}%";
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
    }

    $whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';

    // Get total count
    $countSql = "SELECT COUNT(*) as total FROM messegedetails {$whereClause}";
    $countStmt = $pdo->prepare($countSql);
    $countStmt->execute($params);
    $totalCount = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];

    // Get messages - use direct integer values in query (safe since we validated them)
    $sql = "SELECT id, title, subheading, mobile, type, device_id, date as created_at 
            FROM messegedetails 
            {$whereClause}
            ORDER BY date DESC 
            LIMIT {$limit} OFFSET {$offset}";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $totalPages = $totalCount > 0 ? ceil($totalCount / $limit) : 1;

    echo json_encode([
        'success' => true,
        'status' => true,
        'messages' => $messages,
        'pagination' => [
            'current_page' => $page,
            'total_pages' => $totalPages,
            'total_count' => (int)$totalCount,
            'per_page' => $limit,
            'has_more' => $page < $totalPages
        ]
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
