<?php

require './core.php';

header('Content-Type: application/json');

$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['popup_id']) || !isset($input['action'])) {
    echo json_encode(['success' => false, 'error' => 'Missing parameters']);
    exit;
}

$popup_id = intval($input['popup_id']);
$action = $input['action'];
$user_ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];

try {
    $connect;
    
    if ($action === 'view') {
        // Track view
        $stmt = $connect->prepare("INSERT INTO popup_views (popup_id, user_ip, user_agent) VALUES (?, ?, ?)");
        $stmt->execute([$popup_id, $user_ip, $user_agent]);
    } elseif ($action === 'click') {
        // Track click
        $stmt = $connect->prepare("INSERT INTO popup_clicks (popup_id, user_ip) VALUES (?, ?)");
        $stmt->execute([$popup_id, $user_ip]);
    }
    
    echo json_encode(['success' => true]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}

?>
