<?php
require_once dirname(__DIR__) . '/cong.php';
require_once dirname(__DIR__) . '/lib/DbHelper.php';
require_once dirname(__DIR__) . '/lib/Cloak/VisitorLogAnalytics.php';

session_start();

header('Content-Type: application/json; charset=utf-8');

if (empty($_SESSION['password']) || $_SESSION['password'] != LOGIN_PASSWORD) {
    http_response_code(403);
    echo json_encode(['code' => 1, 'msg' => '未授权', 'data' => null], JSON_UNESCAPED_UNICODE);
    exit;
}

$conn = new mysqli('localhost', DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
    echo json_encode(['code' => 1, 'msg' => '数据库连接失败', 'data' => null], JSON_UNESCAPED_UNICODE);
    exit;
}

$filters = [
    'date_from'   => $_GET['date_from'] ?? '',
    'date_to'     => $_GET['date_to'] ?? '',
    'domain'      => $_GET['domain'] ?? '',
    'campagin_id' => $_GET['campagin_id'] ?? '',
];

$data = VisitorLogAnalytics::buildReport($conn, $filters);
$conn->close();

echo json_encode([
    'code' => 0,
    'msg'  => 'success',
    'data' => $data,
], JSON_UNESCAPED_UNICODE);
