<?php
header('Content-Type: application/json');
require_once 'db.php'; // Your DB connection

$action = $_POST['action'] ?? '';
if ($action === 'read') {
    $page   = max(1, intval($_POST['page'] ?? 1));
    $limit  = max(1, intval($_POST['limit'] ?? 10));
    $search = trim($_POST['search'] ?? '');
    $offset = ($page - 1) * $limit;

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

    if ($search !== '') {
        $where = "WHERE name LIKE ? OR email LIKE ? OR contact LIKE ?";
        $params = ["%$search%", "%$search%", "%$search%"];
    }

    // Count total
    $countStmt = $pdo->prepare("SELECT COUNT(*) as total FROM patients $where");
    $countStmt->execute($params);
    $total = $countStmt->fetchColumn();

    // Fetch rows
    $sql = "SELECT id, name, email, contact, gender, age, blood_group, last_visit, status
            FROM patients $where
            ORDER BY last_visit DESC
            LIMIT $limit OFFSET $offset";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'status' => 'success',
        'data' => $rows,
        'total' => $total,
        'page' => $page,
        'limit' => $limit,
        'totalPages' => ceil($total / $limit)
    ]);
    exit;
}

echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
