<?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);
$property_id = intval($data['property_id'] ?? 0);

if ($property_id <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing or invalid property_id']);
    exit;
}

try {
    $stmt = $mysqli->prepare("SELECT id, title, description, price, type, address, city, state, bedrooms, bathrooms, image_url FROM properties WHERE id = ? AND broker_id = ?");
    if (!$stmt) {
        throw new Exception('Prepare failed: ' . $mysqli->error);
    }
    $stmt->bind_param('ii', $property_id, $broker_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $existing = $result->fetch_assoc();
    $stmt->close();

    if (!$existing) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Property not found']);
        exit;
    }

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

    $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
        )
    ");

    $insert = $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 (?, ?, 'update', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
    ");
    if (!$insert) {
        throw new Exception('Prepare failed: ' . $mysqli->error);
    }

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

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

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

$mysqli->close();
?>
