<?php
/**
 * Broker - Upload Documents/Media
 * POST: Allows broker to upload documents, images, and media for admin approval
 */

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 broker_documents 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 {
    if (!isset($_FILES['document']) || $_FILES['document']['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['success' => false, 'message' => 'No file uploaded or upload error']);
        exit;
    }

    $file = $_FILES['document'];
    $document_name = $_POST['document_name'] ?? $file['name'];
    $property_id = isset($_POST['property_id']) ? (int)$_POST['property_id'] : null;
    if ($property_id !== null && $property_id <= 0) {
        $property_id = null;
    }
    $document_type = $_POST['document_type'] ?? pathinfo($file['name'], PATHINFO_EXTENSION);

    // Validate file
    $max_size = 50 * 1024 * 1024; // 50MB
    if ($file['size'] > $max_size) {
        echo json_encode(['success' => false, 'message' => 'File size exceeds limit (50MB)']);
        exit;
    }

    // Allowed file types
    $allowed_types = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'jpg', 'jpeg', 'png', 'gif', 'webp', 'mp4', 'avi', 'mov'];
    $file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($file_ext, $allowed_types)) {
        echo json_encode(['success' => false, 'message' => 'File type not allowed']);
        exit;
    }

    // Create upload directory if it doesn't exist
    $upload_dir_abs = __DIR__ . '/../../uploads/broker_documents/' . $broker_id . '/';
    $upload_dir_rel = 'uploads/broker_documents/' . $broker_id . '/';
    if (!is_dir($upload_dir_abs)) {
        mkdir($upload_dir_abs, 0755, true);
    }

    // Generate unique filename
    $filename = $broker_id . '_' . time() . '_' . basename($file['name']);
    $file_path_abs = $upload_dir_abs . $filename;
    $file_path_rel = $upload_dir_rel . $filename;

    if (!move_uploaded_file($file['tmp_name'], $file_path_abs)) {
        echo json_encode(['success' => false, 'message' => 'Failed to upload file']);
        exit;
    }

    // Insert into database
    $stmt = $conn->prepare("
        INSERT INTO broker_documents (broker_id, property_id, document_name, document_type, file_path, file_size, approval_status)
        VALUES (?, ?, ?, ?, ?, ?, 'pending')
    ");
    $stmt->bind_param('iisssi', $broker_id, $property_id, $document_name, $file_ext, $file_path_rel, $file['size']);
    $stmt->execute();
    $document_id = $stmt->insert_id;
    $stmt->close();

    echo json_encode([
        'success' => true,
        'message' => 'Document uploaded and submitted for admin approval',
        'document_id' => $document_id,
        'file_path' => $file_path_rel
    ]);

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