<?php
/**
 * TOPBD API — Listing Click & Heart Endpoints
 */

header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';

$action = $_POST['action'] ?? $_GET['action'] ?? 'click';
$listingId = (int)($_POST['listing_id'] ?? $_GET['listing_id'] ?? 0);

if ($listingId <= 0) {
    json_response(['success' => false, 'message' => 'Invalid listing ID'], 400);
}

$db = get_db();

if ($action === 'click') {
    $stmt = $db->prepare("UPDATE listings SET clicks = clicks + 1 WHERE id = ?");
    $stmt->execute([$listingId]);

    $countStmt = $db->prepare("SELECT clicks FROM listings WHERE id = ?");
    $countStmt->execute([$listingId]);
    $clicks = (int)$countStmt->fetchColumn();

    json_response(['success' => true, 'clicks' => $clicks]);
} elseif ($action === 'heart') {
    // Session deduplication check
    $sessionHearts = $_SESSION['hearted_listings'] ?? [];
    $isHearted = in_array($listingId, $sessionHearts, true);

    if ($isHearted) {
        // Toggle off
        $stmt = $db->prepare("UPDATE listings SET hearts = GREATEST(0, hearts - 1) WHERE id = ?");
        $stmt->execute([$listingId]);
        $_SESSION['hearted_listings'] = array_diff($sessionHearts, [$listingId]);
        $hearted = false;
    } else {
        // Add heart
        $stmt = $db->prepare("UPDATE listings SET hearts = hearts + 1 WHERE id = ?");
        $stmt->execute([$listingId]);
        $_SESSION['hearted_listings'][] = $listingId;
        $hearted = true;
    }

    $countStmt = $db->prepare("SELECT hearts FROM listings WHERE id = ?");
    $countStmt->execute([$listingId]);
    $hearts = (int)$countStmt->fetchColumn();

    json_response(['success' => true, 'hearts' => $hearts, 'isHearted' => $hearted]);
} else {
    json_response(['success' => false, 'message' => 'Unknown action'], 400);
}
