<?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');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => false, 'success' => 'Invalid request method']);
    exit;
}

// Include the database configuration file
require_once 'db/config.php';

// Input sanitization
$user_id = filter_input(INPUT_POST, 'user_id', FILTER_SANITIZE_STRING);
$auth    = filter_input(INPUT_POST, 'auth', FILTER_SANITIZE_STRING);
$date_t  = date("Y-m-d H:i:s");

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

// Verify user
$stmt = $con->prepare("SELECT * FROM users WHERE user_id = ? AND auth = ?");
$stmt->bind_param("ss", $user_id, $auth);

if ($stmt->execute()) {
    $result = $stmt->get_result();

    if ($result->num_rows === 1) {

        $data = $result->fetch_assoc();

        // Check package type and required fields
        $requiredFields = [
            'dob', 'height', 'body_color', 'city', 'state',
            'profession', 'denomination', 'hobbies',
            'books', 'movies', 'activities'
        ];

     /*   if ($data['package'] !== 'Free') {
            foreach ($requiredFields as $field) {
                if (empty($data[$field])) {
                    echo json_encode([
                        'status' => false,
                        'success' => 'More info needed',
                        'missing_field' => $field
                    ]);
                    exit;
                }
            }
        }*/

        // Update last seen and online status
        $stmt2 = $con->prepare("UPDATE users SET last_seen = ?, is_online = 1 WHERE user_id = ?");
        $stmt2->bind_param("ss", $date_t, $user_id);
        $stmt2->execute();

        echo json_encode(['status' => true, 'success' => 'Success', 'data' => $data]);

    } else {
        echo json_encode(['status' => false, 'success' => 'User not found', 'data' => []]);
    }

} else {
    error_log('Database error: ' . $stmt->error);
    echo json_encode(['status' => false, 'success' => 'Internal server error']);
}

// Close statement & connection
$stmt->close();
$con->close();
?>
