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

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

try {
    $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)
    )";
    $mysqli->query($create_table);

    $stmt = $mysqli->prepare("
        SELECT
            d.id,
            d.broker_id,
            d.property_id,
            d.document_name,
            d.document_type,
            d.file_path,
            d.file_size,
            d.approval_status,
            d.admin_notes,
            d.uploaded_at,
            d.approved_at,
            COALESCE(u.full_name, CONCAT('Broker #', d.broker_id)) AS broker_name,
            COALESCE(p.title, 'N/A') AS property_title
        FROM broker_documents d
        LEFT JOIN users u ON u.id = d.broker_id
        LEFT JOIN properties p ON p.id = d.property_id
        WHERE d.approval_status = 'pending'
        ORDER BY d.uploaded_at DESC
        LIMIT 150
    ");
    if (!$stmt) {
        throw new Exception('Prepare failed: ' . $mysqli->error);
    }
    $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) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}

$mysqli->close();
?>
