<?php
/**
 * Endpoint for tracking link clicks
 */

// Set headers for CORS if needed
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

// Only process POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); // Method Not Allowed
    echo json_encode(['status' => 'error', 'message' => 'Only POST method is allowed']);
    exit;
}

// Include required files
require_once 'includes/db.php';
require_once 'includes/tracking_functions.php';

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

// Fallback to form data if JSON is not provided
if (json_last_error() !== JSON_ERROR_NONE) {
    $input = $_POST;
}

// Validate required fields
if (empty($input['url'])) {
    http_response_code(400); // Bad Request
    echo json_encode(['status' => 'error', 'message' => 'URL is required']);
    exit;
}

// Get URL and title from input
$url = $input['url'];
$title = $input['title'] ?? '';

// Track the click
$result = trackLinkClick($url, $title);

// Send response
if ($result) {
    echo json_encode([
        'status' => 'success',
        'message' => 'Click tracked successfully',
        'data' => [
            'url' => $url,
            'title' => $title
        ]
    ]);
} else {
    http_response_code(500); // Internal Server Error
    echo json_encode([
        'status' => 'error',
        'message' => 'Failed to track click',
        'data' => [
            'url' => $url
        ]
    ]);
}
