<?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']);
$data = json_decode(file_get_contents('php://input'), true);

$title = trim($data['title'] ?? '');
$description = trim($data['description'] ?? '');
$price = floatval($data['price'] ?? 0);
$type = trim($data['type'] ?? '');
$address = trim($data['address'] ?? '');
$city = trim($data['city'] ?? '');
$state = trim($data['state'] ?? '');
$bedrooms = intval($data['bedrooms'] ?? 0);
$bathrooms = intval($data['bathrooms'] ?? 0);
$image_url = trim($data['image_url'] ?? '');

if ($title === '' || $type === '' || $price <= 0 || $address === '' || $city === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Required fields: title, type, price, address, city']);
    exit;
}

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("
        INSERT INTO property_approval_requests
        (property_id, broker_id, request_type, title, description, price, type, address, city, state, bedrooms, bathrooms, image_url, approval_status)
        VALUES (NULL, ?, 'new_listing', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
    ");
    if (!$stmt) {
        throw new Exception('Prepare failed: ' . $mysqli->error);
    }

    $stmt->bind_param(
        'issdssssiis',
        $broker_id,
        $title,
        $description,
        $price,
        $type,
        $address,
        $city,
        $state,
        $bedrooms,
        $bathrooms,
        $image_url
    );

    if (!$stmt->execute()) {
        throw new Exception('Execute failed: ' . $stmt->error);
    }

    echo json_encode([
        'success' => true,
        'message' => 'Listing submitted for admin approval',
        'request_id' => $stmt->insert_id
    ]);
    $stmt->close();
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}

$mysqli->close();
?>
