<?php
session_start();
require_once 'includes/functions.php';

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

$action = $_GET['action'] ?? '';

requireLogin();
$user = currentUser();

if ($action === 'file_info') {
    $id = $_GET['id'] ?? '';
    $file = getFileById($id);

    if (!$file) {
        echo json_encode(['success' => false, 'msg' => 'Dosya bulunamadı']);
        exit;
    }

    $versions = getFileVersions($id);
    $verList = [];
    foreach ($versions as $v) {
        $verList[] = [
            'id'            => $v['id'],
            'version'       => (int)($v['version'] ?? 1),
            'original_name' => $v['original_name'],
            'size'          => (int)$v['size'],
            'uploaded_at'   => $v['uploaded_at'],
            'icon'          => getMimeIcon($v['mime'], $v['ext']),
        ];
    }

    $ownerName = '';
    if (!empty($file['owner_id'])) {
        $owner = getUserById($file['owner_id']);
        $ownerName = $owner ? ($owner['display_name'] ?? $owner['username'] ?? '') : '';
    }
    $resp = [
        'success' => true,
        'file'    => [
            'id'            => $file['id'],
            'original_name' => $file['original_name'],
            'size'          => (int)$file['size'],
            'mime'          => $file['mime'],
            'ext'           => $file['ext'],
            'icon'          => getMimeIcon($file['mime'], $file['ext']),
            'previewable'   => isPreviewable($file['mime']),
            'uploaded_at'   => $file['uploaded_at'],
            'expire_label'  => formatExpire($file),
            'area'          => $file['area'],
            'sender_email'  => $file['sender_email'] ?? '',
            'message'       => $file['message'] ?? '',
            'version'       => (int)($file['version'] ?? 1),
            'versions'      => count($verList) > 1 ? $verList : [],
            'code_zipped'   => !empty($file['code_zipped']),
            'original_ext'  => $file['original_ext'] ?? '',
            'owner_name'    => $ownerName,
        ]
    ];
    echo json_encode($resp);
    exit;
}

if ($action === 'batch_delete') {
    verifyCsrfToken();
    $ids = $_POST['ids'] ?? '';
    if (!$ids) {
        echo json_encode(['success' => false, 'msg' => 'Dosya seçilmedi.']);
        exit;
    }
    $idArr = explode(',', $ids);
    $deleted = 0;
    $deletedNames = [];
    foreach ($idArr as $fid) {
        $fid = trim($fid);
        $file = getFileById($fid);
        if ($file && (
            ($file['area'] === 'common')
            || ($file['owner_id'] ?? '') === $user['id']
            || ($file['recipient_id'] ?? '') === $user['id'])
        ) {
            $deletedNames[] = $file['original_name'] ?? 'Bilinmiyor';
            if (deleteFile($fid)) $deleted++;
        }
    }
    if ($deleted > 0) {
        $who = $_SESSION['username'] ?? 'Sistem';
        addSystemLog('batch_delete', $who . ' toplu silme yaptı (' . $deleted . ' dosya): ' . implode(', ', $deletedNames), $_SESSION['user_id'] ?? null);
    }
    echo json_encode(['success' => true, 'deleted' => $deleted, 'msg' => "$deleted dosya silindi."]);
    exit;
}

echo json_encode(['success' => false, 'msg' => 'Geçersiz istek']);
