<?php
require_once 'auth_check.php';
require_once 'db.php';
session_start();

header('Content-Type: application/json');

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

try {
    if (!isset($_FILES['file']) || !isset($_POST['path'])) {
        throw new Exception('Missing parameters');
    }

    $db = getDB1Connection();
    $query = $db->prepare("SELECT staff_directory FROM utilisateurs WHERE id = ?");
    $query->execute([$_SESSION['user_id']]);
    $result = $query->fetch(PDO::FETCH_ASSOC);
    
    if (!$result || !$result['staff_directory']) {
        throw new Exception('Staff directory not configured');
    }

    $rootPath = $result['staff_directory'];
    $uploadPath = $rootPath . $_POST['path'];

    if (!str_starts_with(realpath($uploadPath), realpath($rootPath))) {
        throw new Exception('Access denied');
    }

    $file = $_FILES['file'];
    $targetPath = $uploadPath . '/' . basename($file['name']);

    if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
        throw new Exception('Failed to upload file');
    }

    echo json_encode([
        'success' => true,
        'file' => [
            'name' => basename($file['name']),
            'path' => str_replace($rootPath, '', $targetPath),
            'type' => getFileType($file['name']),
            'size' => filesize($targetPath),
            'modified' => date('Y-m-d H:i:s')
        ]
    ]);

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

function getFileType($filename) {
    $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    $types = [
        'txt' => 'text',
        'md' => 'text',
        'pdf' => 'pdf',
        'jpg' => 'image',
        'jpeg' => 'image',
        'png' => 'image',
        'gif' => 'image'
    ];
    return $types[$extension] ?? 'default';
}