<?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']) || empty($_POST['match_id'])) {
    echo json_encode(['status' => false, 'success' => 'Missing required parameters']);
    exit;
}

$user_id  = check_input($_POST['user_id']);
$auth     = check_input($_POST['auth']);
$match_id = check_input($_POST['match_id']);
$date_t   = date("Y-m-d H:i:s");

// ✅ Verify user
$stmt = $con->prepare("SELECT firstname, lastname, img, city, state, country 
                       FROM users WHERE user_id = ? AND auth = ?");
$stmt->bind_param("ss", $user_id, $auth);
$stmt->execute();
$userResult = $stmt->get_result();

if ($userResult && $userResult->num_rows === 1) {
    $userData = $userResult->fetch_assoc();

    $name    = $userData['firstname'] . " " . $userData['lastname'];
    $img     = $userData['img'];
    $city    = $userData['city'];
    $state   = $userData['state'];
    $country = $userData['country'];

    // ✅ Update current user last_seen + mark online
    $stmt = $con->prepare("UPDATE users SET last_seen = ?, is_online = 1 WHERE user_id = ?");
    $stmt->bind_param("ss", $date_t, $user_id);
    $stmt->execute();

    // ✅ Insert profile view
    $stmt = $con->prepare("INSERT INTO profile_views (user_id, match_id, name, img, city, state, country, date_t) 
                           VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssssss", $match_id, $user_id, $name, $img, $city, $state, $country, $date_t);
    $stmt->execute();

    // ✅ Fetch match user details + check online/offline
    $stmt = $con->prepare("SELECT *, 
                CASE 
                    WHEN TIMESTAMPDIFF(MINUTE, last_seen, NOW()) <= 5 THEN 'online'
                    ELSE 'offline'
                END as online_status
                FROM users WHERE user_id = ?");
    $stmt->bind_param("s", $match_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' => true, 'success' => 'No Match', 'data' => []];
    }
} else {
    $response = ['status' => false, 'success' => 'Invalid user ID or authentication token'];
}

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