<?php
session_start();
require_once "config.php";

if (!isset($_SESSION['user_id'])) {
    http_response_code(403);
    echo json_encode(["error" => "Unauthorized"]);
    exit;
}

$user_id = $_SESSION['user_id'];

// Fetch adverts
$stmt = $conn->prepare("
    SELECT a.*, p.title AS property_title
    FROM adverts a
    JOIN properties p ON a.property_id = p.id
    WHERE a.user_id = ?
    ORDER BY a.created_at DESC
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

$adverts = [];
$total = 0; $active = 0; $expired = 0;

while ($row = $result->fetch_assoc()) {
    $total++;
    if ($row['status'] === "active") $active++;
    if ($row['status'] === "expired") $expired++;
    $adverts[] = $row;
}

$stmt->close();

echo json_encode([
    "counts" => [
        "total" => $total,
        "active" => $active,
        "expired" => $expired
    ],
    "adverts" => $adverts
]);
