<?php
// api/track_click.php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);
$domain_id = (int)($data['domain_id'] ?? 0);
$video_id = $data['video_id'] ?? '';

if ($domain_id > 0) {
    track_visit($pdo, $domain_id, 'click');
    
    // Increment video views if video_id is provided and not already viewed in this session
    if (!empty($video_id)) {
        if (session_status() === PHP_SESSION_NONE) session_start();
        if (!isset($_SESSION['viewed_vids'])) $_SESSION['viewed_vids'] = [];
        
        if (!in_array($video_id, $_SESSION['viewed_vids'])) {
            try {
                $stmt = $pdo->prepare("UPDATE videos SET views = views + 1 WHERE id = ?");
                $stmt->execute([$video_id]);
                $_SESSION['viewed_vids'][] = $video_id;
            } catch (PDOException $e) {
                // Ignore DB errors for tracking
            }
        }
    }
    
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid domain ID']);
}
?>

