<?php
session_start();

// Check if logged in for most endpoints
$publicEndpoints = ['track_visit'];
$endpoint = $_GET['action'] ?? $_POST['action'] ?? '';

if (!in_array($endpoint, $publicEndpoints)) {
    if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
        http_response_code(401);
        echo json_encode(['error' => 'Unauthorized']);
        exit;
    }
}

require_once 'includes/config.php';
require_once 'includes/functions.php';
require_once 'includes/visitor_tracker.php';

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

switch ($endpoint) {
    case 'shorten_url':
        $originalUrl = $_POST['url'] ?? '';
        $customCode = $_POST['custom_code'] ?? '';
        
        if (!filter_var($originalUrl, FILTER_VALIDATE_URL)) {
            echo json_encode(['error' => 'Invalid URL']);
            break;
        }
        
        $result = shortenUrl($originalUrl, $customCode);
        echo json_encode($result);
        break;
        
    case 'get_urls':
        $urls = loadUrls();
        echo json_encode($urls);
        break;
        
    case 'get_visits':
        $filter = $_GET['filter'] ?? 'all';
        $limit = $_GET['limit'] ?? 50;
        $visits = getVisits($filter, $limit);
        echo json_encode($visits);
        break;
        
    case 'get_statistics':
        $stats = getStatistics();
        echo json_encode($stats);
        break;
        
    case 'get_analytics':
        $analytics = getAnalytics();
        echo json_encode($analytics);
        break;
        
    case 'get_recent_visits':
        $limit = $_GET['limit'] ?? 10;
        $since = $_GET['since'] ?? null;
        $visits = getRecentVisits($limit, $since);
        echo json_encode($visits);
        break;
        
    case 'delete_url':
        $shortCode = $_POST['short_code'] ?? '';
        $result = deleteUrl($shortCode);
        echo json_encode($result);
        break;
        
    default:
        http_response_code(400);
        echo json_encode(['error' => 'Invalid action']);
}
?>
