<?php
require_once '../config.php';
header('Content-Type: application/json');

// Check if user is admin
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 10;
$offset = ($page - 1) * $per_page;

try {
    $broker_ref_table = 'users';
    $fk_result = $mysqli->query("
        SELECT LOWER(REFERENCED_TABLE_NAME) AS ref_table
        FROM information_schema.KEY_COLUMN_USAGE
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = 'properties'
          AND COLUMN_NAME = 'broker_id'
          AND REFERENCED_TABLE_NAME IS NOT NULL
        LIMIT 1
    ");
    if ($fk_result && ($fk_row = $fk_result->fetch_assoc())) {
        $ref = strtolower((string)($fk_row['ref_table'] ?? ''));
        if ($ref === 'brokers' || $ref === 'users') {
            $broker_ref_table = $ref;
        }
        $fk_result->free();
    }

    // Get total count
    $count_query = "SELECT COUNT(*) as total FROM properties";
    $count_result = $mysqli->query($count_query);
    
    if (!$count_result) {
        throw new Exception("Count query failed: " . $mysqli->error);
    }
    
    $total = $count_result->fetch_assoc()['total'];

    // Get properties
    $query = $broker_ref_table === 'brokers'
        ? "
            SELECT
                p.id,
                p.title,
                p.type,
                p.price,
                p.address,
                p.city,
                p.bedrooms,
                p.bathrooms,
                p.status,
                p.image_url,
                p.broker_id,
                COALESCE(b.name, 'Unassigned') AS broker_name,
                p.created_at
            FROM properties p
            LEFT JOIN brokers b ON b.id = p.broker_id
            ORDER BY p.created_at DESC
            LIMIT ? OFFSET ?
        "
        : "
            SELECT
                p.id,
                p.title,
                p.type,
                p.price,
                p.address,
                p.city,
                p.bedrooms,
                p.bathrooms,
                p.status,
                p.image_url,
                p.broker_id,
                COALESCE(u.full_name, 'Unassigned') AS broker_name,
                p.created_at
            FROM properties p
            LEFT JOIN users u ON u.id = p.broker_id AND u.role = 'broker'
            ORDER BY p.created_at DESC
            LIMIT ? OFFSET ?
        ";
    $stmt = $mysqli->prepare($query);
    
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $mysqli->error);
    }
    
    $stmt->bind_param('ii', $per_page, $offset);
    
    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }
    
    $result = $stmt->get_result();

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

    echo json_encode([
        'success' => true,
        'properties' => $properties,
        'total' => $total,
        'page' => $page,
        'per_page' => $per_page,
        'total_pages' => ceil($total / $per_page)
    ]);

    $stmt->close();
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}

$mysqli->close();
?>
