<?php
/**
 * Get Broker's Assigned Properties
 * Returns: Properties assigned to the broker
 */

header('Content-Type: application/json');
require_once '../../config.php';
require_once __DIR__ . '/broker-identity.php';

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

$session_broker_id = (int)$_SESSION['user_id'];
$brokerCtx = resolveBrokerContext($conn, $session_broker_id);
$broker_id = (int)$brokerCtx['property_broker_id'];
$fallback_broker_id = $session_broker_id !== $broker_id ? $session_broker_id : 0;

try {
    $conn->query("
        CREATE TABLE IF NOT EXISTS property_assignment_workflow (
            id INT AUTO_INCREMENT PRIMARY KEY,
            property_id INT NOT NULL UNIQUE,
            broker_id INT NULL,
            workflow_status VARCHAR(40) NOT NULL DEFAULT 'assigned',
            admin_review_status VARCHAR(20) NOT NULL DEFAULT 'pending',
            broker_confirmed_at DATETIME NULL,
            work_started_at DATETIME NULL,
            work_finished_at DATETIME NULL,
            admin_reviewed_by INT NULL,
            admin_reviewed_at DATETIME NULL,
            admin_notes VARCHAR(255) NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_broker_id (broker_id),
            INDEX idx_workflow_status (workflow_status),
            INDEX idx_admin_review_status (admin_review_status)
        )
    ");

    $stmt = $conn->prepare("
        SELECT 
            properties.id, properties.title, properties.description, properties.price, properties.type, properties.status, 
            properties.address, properties.city, properties.state, properties.image_url,
            properties.bedrooms, properties.bathrooms, properties.area, properties.created_at,
            (SELECT COUNT(*) FROM inquiries WHERE property_id = properties.id AND status IN ('pending', 'responded')) as inquiry_count,
            COALESCE(aw.workflow_status, CASE WHEN properties.broker_id IS NULL THEN 'unassigned' ELSE 'assigned' END) AS assignment_status,
            COALESCE(aw.admin_review_status, 'pending') AS assignment_review_status
        FROM properties 
        LEFT JOIN property_assignment_workflow aw ON aw.property_id = properties.id
        WHERE (properties.broker_id = ? OR (? > 0 AND properties.broker_id = ?))
        ORDER BY properties.updated_at DESC 
        LIMIT 50
    ");
    $stmt->bind_param('iii', $broker_id, $fallback_broker_id, $fallback_broker_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $properties = [];
    while ($row = $result->fetch_assoc()) {
        $properties[] = $row;
    }
    $stmt->close();

    echo json_encode([
        'success' => true,
        'properties' => $properties,
        'count' => count($properties)
    ]);

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