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

$session_role = $_SESSION['role'] ?? ($_SESSION['user_role'] ?? '');
if (!isset($_SESSION['user_id']) || $session_role !== 'broker') {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

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

try {
    $mysqli->query("
        CREATE TABLE IF NOT EXISTS property_approval_requests (
            id INT AUTO_INCREMENT PRIMARY KEY,
            property_id INT NULL,
            broker_id INT NOT NULL,
            request_type VARCHAR(30) NOT NULL DEFAULT 'update',
            title VARCHAR(255) NULL,
            description TEXT NULL,
            price DECIMAL(12,2) NULL,
            type VARCHAR(50) NULL,
            address VARCHAR(255) NULL,
            city VARCHAR(100) NULL,
            state VARCHAR(100) NULL,
            bedrooms INT NULL,
            bathrooms INT NULL,
            image_url VARCHAR(500) NULL,
            approval_status VARCHAR(20) NOT NULL DEFAULT 'pending',
            admin_price DECIMAL(12,2) NULL,
            admin_notes TEXT NULL,
            reviewed_by INT NULL,
            reviewed_at TIMESTAMP NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )
    ");

    $stmt = $mysqli->prepare("
        SELECT
            r.id,
            r.property_id,
            r.request_type,
            r.title,
            r.price,
            r.type,
            r.address,
            r.city,
            r.state,
            r.approval_status,
            r.admin_price,
            r.admin_notes,
            r.created_at,
            r.reviewed_at,
            r.updated_at,
            COALESCE(p.title, r.title, CONCAT('Property #', r.property_id)) AS property_label
        FROM property_approval_requests r
        LEFT JOIN properties p ON p.id = r.property_id
        WHERE r.broker_id = ?
        ORDER BY r.created_at DESC
        LIMIT 100
    ");
    if (!$stmt) {
        throw new Exception('Prepare failed: ' . $mysqli->error);
    }
    $stmt->bind_param('i', $broker_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $requests = [];
    while ($row = $result->fetch_assoc()) {
        $requests[] = $row;
    }
    $stmt->close();

    echo json_encode([
        'success' => true,
        'requests' => $requests,
        'count' => count($requests)
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}

$mysqli->close();
?>
