<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json');
require_once 'db/config.php'; // should set $con (mysqli)

// Helper function
function clean($val) {
    return htmlspecialchars(stripslashes(trim($val)));
}

// Get inputs
$user_id = isset($_POST['user_id']) ? clean($_POST['user_id']) : '';
$auth    = isset($_POST['auth']) ? clean($_POST['auth']) : '';

if (!$user_id || !$auth) {
    echo json_encode(['status' => false, 'success' => 'Missing user_id or auth']);
    exit;
}

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

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

if (strtoupper($user['package']) === 'FREE') {
    echo json_encode(['status' => false, 'success' => 'Free plan users are not allowed']);
    exit;
}

// Check if today's pick already exists for this user
$today = date('Y-m-d');
$stmt = $con->prepare("SELECT COUNT(*) AS count FROM top_picks WHERE user_id = ? AND pick_date = ?");
$stmt->bind_param("ss", $user_id, $today);
$stmt->execute();
$result = $stmt->get_result();
$row    = $result->fetch_assoc();
$stmt->close();

if ($row['count'] > 0) {
    echo json_encode(['status' => true, 'success' => 'Top picks already generated for you today']);
    exit;
}

// Determine eligible users to pick from
$stmt = $con->prepare("
    SELECT u.user_id 
    FROM users u
    WHERE u.package IN ('Gold','Platinum')
      AND u.user_id != ?
      AND u.user_id NOT IN (
          SELECT match_id FROM likes WHERE user_id = ?
      )
    ORDER BY RAND() 
    LIMIT 10
");
$stmt->bind_param("ss", $user_id, $user_id);

$stmt->execute();
$result = $stmt->get_result();
$users  = [];
while ($row = $result->fetch_assoc()) {
    $users[] = $row;
}
$stmt->close();

if (empty($users)) {
    echo json_encode(['status' => false, 'success' => 'No eligible users found']);
    exit;
}

// Insert picks for this user
$stmt = $con->prepare("INSERT INTO top_picks (user_id, picked_user_id, pick_date) VALUES (?, ?, ?)");
foreach ($users as $u) {
    $stmt->bind_param("sss", $user_id, $u['user_id'], $today);
    $stmt->execute();
}
$stmt->close();

echo json_encode([
    'status'  => true,
    'success' => 'Top picks generated successfully',
    'data'    => $users
]);

$con->close();
?>
