<?php
declare(strict_types=1);
require_once __DIR__ . '/../db/config.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$input = json_decode(file_get_contents('php://input'), true);
$username = $input['username'] ?? null;
$phone = $input['phone'] ?? null;
$session_id = session_id();

if (!empty($session_id) && ($username || $phone)) {
    $db = db();
    
    // Check if entry exists for this session
    $stmt = $db->prepare("SELECT id FROM visitor_logs WHERE session_id = ? ORDER BY id DESC LIMIT 1");
    $stmt->execute([$session_id]);
    $visitor = $stmt->fetch();
    
    if ($visitor) {
        if ($username && $phone) {
            $stmt = $db->prepare("UPDATE visitor_logs SET username = ?, phone_number = ?, last_activity = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$username, $phone, $visitor['id']]);
        } elseif ($username) {
            $stmt = $db->prepare("UPDATE visitor_logs SET username = ?, last_activity = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$username, $visitor['id']]);
        } else {
            $stmt = $db->prepare("UPDATE visitor_logs SET phone_number = ?, last_activity = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$phone, $visitor['id']]);
        }
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'error' => 'No session found']);
    }
} else {
    echo json_encode(['success' => false, 'error' => 'Invalid data']);
}
