
­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');

require_once __DIR__ . '/db.php';

define('API_KEY', 'EDSfnoewiewfibsdv5ewf7');

$headers = function_exists('getallheaders') ? getallheaders() : [];

$providedKey = '';

if (isset($headers['X-API-KEY'])) {
    $providedKey = $headers['X-API-KEY'];
}

if (isset($_GET['api_key'])) {
    $providedKey = $_GET['api_key'];
}

if ($providedKey !== API_KEY) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized'
    ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit;
}

$limit  = isset($_GET['limit']) ? (int)$_GET['limit'] : 50;
$offset = isset($_GET['offset']) ? (int)$_GET['offset'] : 0;

$limit  = max(1, min($limit, 500));
$offset = max(0, $offset);

$table = 'leads3'; // change if your table name is different

$response = [
    'success' => false,
    'total' => 0,
    'limit' => $limit,
    'offset' => $offset,
    'data' => []
];

$countSql = "SELECT COUNT(*) AS total FROM `{$table}`";
$countResult = $conn->query($countSql);

if (!$countResult) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Count query failed',
        'error' => $conn->error
    ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit;
}

$response['total'] = (int)$countResult->fetch_assoc()['total'];

$sql = "
    SELECT
        `id`,
        `utm_source`,
        `utm_campaign`,
        `formtype`,
        `offer_id`,
        `fullName`,
        `lastname`,
        `email`,
        `mobile`,
        `salary`,
        `model`,
        `nationality`,
        `bank`,
        `gender`,
        `city`,
        `branch`,
        `obligation`,
        `realestateLoan`,
        `obligationAmount`,
        `purchaseTime`,
        `terms`,
        `created_at`,
        `otp`,
        `otpVerified`,
        `campaign`,
        `sourcee`,
        `message`,
        `success`,
        `reference_id`
    FROM `{$table}`
    ORDER BY `id` DESC
    LIMIT {$offset}, {$limit}
";

$result = $conn->query($sql);

if (!$result) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Data query failed',
        'error' => $conn->error,
        'sql' => $sql
    ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit;
}

while ($row = $result->fetch_assoc()) {
    $response['data'][] = $row;
}

$response['success'] = true;
$response['count'] = count($response['data']);

echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;