<?php
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');
require 'db/config.php';

$user_id = $_POST['user_id'] ?? '';
$auth    = $_POST['auth'] ?? '';

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

// Connect directly to DB
try {
    $conn = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'success' => false, 'message' => 'Database connection failed']);
    exit;
}

// Verify user and get package
$sql = "SELECT package FROM users WHERE user_id = ? AND auth = ?";
$stmt = $conn->prepare($sql);
$stmt->execute([$user_id, $auth]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

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

if ($user['package'] === 'Free') {
    echo json_encode(['status' => 'error', 'success' => false, 'message' => 'This feature is not available. Upgrade plan']);
    exit;
}

// Get likes from last 7 days
$sql = "SELECT match_id, name, img, city, state, country, date_t 
        FROM likes 
        WHERE user_id = ? 
          AND STR_TO_DATE(date_t, '%Y-%m-%d') >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
        ORDER BY STR_TO_DATE(date_t, '%Y-%m-%d') DESC";

$stmt = $conn->prepare($sql);
$stmt->execute([$user_id]);
$likes = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($likes)) {
    echo json_encode([
        'status'  => 'success',
        'success' => true,
        'message' => 'No likes found in the last 7 days',
        'data'    => []
    ]);
} else {
    echo json_encode([
        'status'  => 'success',
        'success' => true,
        'data'    => $likes
    ]);
}
?>
