<?php
require "../config/database.php";
require "../includes/auth.php";
require "../includes/csrf.php";

error_reporting(0);

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

$viewerId = (int)$_SESSION["user"]["id"];
$method = $_SERVER["REQUEST_METHOD"] ?? "GET";

if ($method === "POST") {
    $data = json_decode(file_get_contents("php://input"), true);
    if (!is_array($data)) {
        http_response_code(400);
        echo json_encode(["success" => false, "error" => "invalid_payload"]);
        exit;
    }

    if (!requireCsrfFromPayload($data, "csrf")) {
        http_response_code(403);
        echo json_encode(["success" => false, "error" => "invalid_csrf"]);
        exit;
    }

    $workerId = (int)($data["worker_id"] ?? 0);
    if ($workerId <= 0) {
        http_response_code(422);
        echo json_encode(["success" => false, "error" => "worker_id_required"]);
        exit;
    }

    $workerUserStmt = $pdo->prepare("SELECT user_id FROM workers WHERE id = ? LIMIT 1");
    $workerUserStmt->execute([$workerId]);
    $viewedUserId = (int)$workerUserStmt->fetchColumn();

    if ($viewedUserId <= 0) {
        http_response_code(404);
        echo json_encode(["success" => false, "error" => "worker_not_found"]);
        exit;
    }

    $stmt = $pdo->prepare("
        INSERT INTO profile_views (viewer_id, worker_id, viewed_at)
        VALUES (?, ?, NOW())
    ");
    $stmt->execute([$viewerId, $viewedUserId]);

    echo json_encode(["success" => true]);
    exit;
}

$targetUserId = (int)($_GET["user_id"] ?? $viewerId);

$stmt = $pdo->prepare("
    SELECT COUNT(*) FROM profile_views WHERE worker_id = ?
");
$stmt->execute([$targetUserId]);
$total = (int)$stmt->fetchColumn();

$recentStmt = $pdo->prepare("
    SELECT pv.id, pv.viewer_id, pv.worker_id, pv.viewed_at, u.email AS viewer_email
    FROM profile_views pv
    LEFT JOIN users u ON u.id = pv.viewer_id
    WHERE pv.worker_id = ?
    ORDER BY pv.id DESC
    LIMIT 50
");
$recentStmt->execute([$targetUserId]);

echo json_encode([
    "success" => true,
    "data" => [
        "total" => $total,
        "recent" => $recentStmt->fetchAll(PDO::FETCH_ASSOC)
    ]
]);
