<?php
/**
 * Get Broker's Documents
 * Returns: Documents uploaded by broker with their approval status
 */

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

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

$broker_id = $_SESSION['user_id'];

// Ensure table exists
$create_table = "CREATE TABLE IF NOT EXISTS broker_documents (
    id INT AUTO_INCREMENT PRIMARY KEY,
    broker_id INT NOT NULL,
    property_id INT,
    document_name VARCHAR(255) NOT NULL,
    document_type VARCHAR(50),
    file_path VARCHAR(500) NOT NULL,
    file_size INT,
    approval_status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending',
    admin_notes TEXT,
    uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    approved_at TIMESTAMP NULL,
    FOREIGN KEY(broker_id) REFERENCES users(id),
    FOREIGN KEY(property_id) REFERENCES properties(id)
)";
$conn->query($create_table);

try {
    $stmt = $conn->prepare("
        SELECT 
            id, property_id, document_name, document_type, file_path, file_size,
            approval_status, admin_notes, uploaded_at, approved_at
        FROM broker_documents 
        WHERE broker_id = ? 
        ORDER BY uploaded_at DESC 
        LIMIT 100
    ");
    $stmt->bind_param('i', $broker_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $documents = [];
    while ($row = $result->fetch_assoc()) {
        $documents[] = $row;
    }
    $stmt->close();

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

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