<?php
session_start();
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json; charset=utf-8');

include 'db/config.php';

function check_input($par) {
    return htmlspecialchars(stripslashes(trim($par)));
}

if (empty($_POST['user_id']) || empty($_POST['auth'])) {
    echo json_encode(['status' => false, 'success' => 'Missing required parameters']);
    exit;
}

$user_id = check_input($_POST['user_id']);
$auth    = check_input($_POST['auth']);

// Verify user exists
$stmt = $con->prepare("SELECT package, package_expiry FROM users WHERE user_id = ? AND auth = ?");
$stmt->bind_param("ss", $user_id, $auth);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if (!$user) {
    echo json_encode(['status' => false, 'success' => 'Invalid user ID or authentication token']);
    exit;
}

// Check package
/*if (strtoupper($user['package']) === 'Free') {
    echo json_encode(['status' => false, 'success' => 'No permission']);
    exit;
}*/

// If package is valid, run query
$stmt = $con->prepare("SELECT * FROM matches WHERE user_id = ? ORDER BY id DESC LIMIT 100");
$stmt->bind_param("s", $user_id);
$stmt->execute();
$activityResult = $stmt->get_result();

$data = [];
while ($row = $activityResult->fetch_assoc()) {
    $data[] = $row;
}

if (!empty($data)) {
    $response = ['status' => true, 'success' => 'Success', 'data' => $data];
} else {
    $response = ['status' => false, 'success' => 'No Match Found', 'data' => []];
}

$con->close();
echo json_encode($response);
?>
