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

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

$agent_id = intval($_SESSION['user_id']);

// Pagination setup
$limit = 10;
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$filter = isset($_GET['filter']) ? $_GET['filter'] : 'all';
$offset = ($page - 1) * $limit;

// Base condition (restrict to agent only)
$where = "user_id = $agent_id";

// Filter handling
$validCategories = ['residential', 'commercial', 'land', 'other'];
if ($filter !== 'all') {
    if (in_array($filter, ['sale', 'rent'])) {
        $where .= " AND type = '$filter'";
    } elseif (in_array($filter, $validCategories)) {
        $where .= " AND category = '$filter'";
    }
}

// Get counts (for quick stats)
$stats = [
    'total'   => 0,
    'sale'    => 0,
    'rent'    => 0,
];
$statsQuery = $conn->query("
    SELECT type, COUNT(*) AS cnt 
    FROM properties 
    WHERE user_id = $agent_id 
    GROUP BY type
");
while ($row = $statsQuery->fetch_assoc()) {
    $stats[strtolower($row['type'])] = intval($row['cnt']);
    $stats['total'] += intval($row['cnt']);
}

// Get total rows for pagination
$totalRowsQuery = $conn->query("SELECT COUNT(*) AS cnt FROM properties WHERE $where");
$totalRows = $totalRowsQuery->fetch_assoc()['cnt'];
$totalPages = ceil($totalRows / $limit);

// Fetch properties (with preview image)
$sql = "
    SELECT p.*, 
           (SELECT image_path 
            FROM property_images 
            WHERE property_id = p.id 
            LIMIT 1) AS main_image
    FROM properties p
    WHERE $where
    ORDER BY p.id DESC
    LIMIT $offset, $limit
";
$result = $conn->query($sql);

$properties = [];
while ($row = $result->fetch_assoc()) {
    $properties[] = $row;
}

// Send JSON response
echo json_encode([
    'stats'       => $stats,
    'properties'  => $properties,
    'currentPage' => $page,
    'totalPages'  => $totalPages
]);
