<?php
// ============================================================
//  ajax/upload_file.php  —  File Upload & Delete
//  Fixed: auto-creates draft if submission_id=0
// ============================================================
require_once __DIR__ . '/../config/db.php';
startSession();

header('Content-Type: application/json');
$userId = getCurrentUserId();

// ── DELETE ────────────────────────────────────────────────────
if (($_POST['action'] ?? '') === 'delete') {
    $fileId = (int)($_POST['file_id'] ?? 0);
    if (!$fileId) jsonResponse(false, 'File ID required');

    $stmt = db()->prepare(
        "SELECT sf.*, s.user_id
         FROM submission_files sf
         JOIN submissions s ON s.submission_id = sf.submission_id
         WHERE sf.file_id = ?"
    );
    $stmt->execute([$fileId]);
    $file = $stmt->fetch();

    if (!$file || (int)$file['user_id'] !== $userId) {
        jsonResponse(false, 'File not found or access denied');
    }

    $fullPath = UPLOAD_BASE . ltrim($file['stored_path'], '/');
    if (file_exists($fullPath)) @unlink($fullPath);

    db()->prepare("DELETE FROM submission_files WHERE file_id = ?")->execute([$fileId]);
    jsonResponse(true, 'File deleted');
}

// ── UPLOAD ────────────────────────────────────────────────────
if (!isset($_FILES['file'])) {
    jsonResponse(false, 'No file received. Please select a file to upload.');
}

$submissionId = (int)($_POST['submission_id'] ?? 0);
$fileType     = trim($_POST['file_type'] ?? '');

// ── Auto-create draft if no submission_id ─────────────────────
// This is the key fix: if submission_id=0, create a draft first
if (!$submissionId) {
    try {
        $stmt = db()->prepare(
            "INSERT INTO submissions
               (user_id, status, is_draft, completion_score, created_at, updated_at)
             VALUES (?, 'draft', 1, 0, NOW(), NOW())"
        );
        $stmt->execute([$userId]);
        $submissionId = (int)db()->lastInsertId();
    } catch (PDOException $e) {
        jsonResponse(false, 'Could not create draft: ' . $e->getMessage());
    }
}

// Allowed types
$allowedTypes = [
    'manuscript'     => ALLOWED_MANUSCRIPT,
    'manuscript_pdf' => ['pdf'],
    'figure'         => ALLOWED_FIGURES,
    'supplementary'  => ALLOWED_OTHER,
    'review_only'    => ALLOWED_OTHER,
];

if (!array_key_exists($fileType, $allowedTypes)) {
    jsonResponse(false, 'Invalid file type: ' . $fileType);
}

$file     = $_FILES['file'];
$origName = basename($file['name']);
$ext      = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
$mimeType = $file['type'];
$sizeKB   = (int)ceil($file['size'] / 1024);

// Check upload error
if ($file['error'] !== UPLOAD_ERR_OK) {
    $errors = [
        UPLOAD_ERR_INI_SIZE   => 'File exceeds server upload limit (php.ini upload_max_filesize)',
        UPLOAD_ERR_FORM_SIZE  => 'File exceeds form size limit',
        UPLOAD_ERR_PARTIAL    => 'File was only partially uploaded',
        UPLOAD_ERR_NO_FILE    => 'No file was uploaded',
        UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary folder on server',
        UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
    ];
    $msg = $errors[$file['error']] ?? 'Unknown upload error code: ' . $file['error'];
    jsonResponse(false, $msg);
}

// Validate extension
if (!in_array($ext, $allowedTypes[$fileType])) {
    jsonResponse(false,
        'File type .' . $ext . ' is not allowed for ' . $fileType . '. ' .
        'Allowed: ' . implode(', ', $allowedTypes[$fileType])
    );
}

// Validate size (50MB)
if ($file['size'] > MAX_FILE_SIZE) {
    jsonResponse(false, 'File too large (' . round($file['size']/1048576,1) . 'MB). Maximum is 50MB.');
}

// Verify ownership
$stmt = db()->prepare("SELECT user_id FROM submissions WHERE submission_id = ?");
$stmt->execute([$submissionId]);
$subOwner = $stmt->fetchColumn();
if (!$subOwner || (int)$subOwner !== $userId) {
    jsonResponse(false, 'Access denied. This submission does not belong to you.');
}

// PDF manuscript → goes to manuscript_pdf type
$actualType = $fileType;
if ($fileType === 'manuscript' && $ext === 'pdf') {
    $actualType = 'manuscript_pdf';
}
$isEditable = in_array($ext, ['doc','docx','tex','bib']) ? 1 : 0;

// Create upload directory
$subDir = UPLOAD_BASE . $actualType . DIRECTORY_SEPARATOR . $submissionId . DIRECTORY_SEPARATOR;
if (!is_dir($subDir)) {
    if (!mkdir($subDir, 0755, true)) {
        jsonResponse(false, 'Cannot create upload directory. Check server folder permissions on: ' . UPLOAD_BASE);
    }
}

// Sanitize filename & make unique
$safeName   = preg_replace('/[^a-zA-Z0-9._-]/', '_', $origName);
$uniqueName = time() . '_' . $safeName;
$destPath   = $subDir . $uniqueName;
$storedPath = $actualType . '/' . $submissionId . '/' . $uniqueName;

if (!move_uploaded_file($file['tmp_name'], $destPath)) {
    jsonResponse(false,
        'Failed to save file. Check write permissions on: ' . $subDir
    );
}

// Save to DB
try {
    $stmt = db()->prepare(
        "INSERT INTO submission_files
           (submission_id, file_type, original_name, stored_path,
            mime_type, file_size_kb, is_editable_version, uploaded_at)
         VALUES (?,?,?,?,?,?,?,NOW())"
    );
    $stmt->execute([
        $submissionId, $actualType, $origName,
        $storedPath, $mimeType, $sizeKB, $isEditable
    ]);
    $fileId = (int)db()->lastInsertId();

    jsonResponse(true, 'File uploaded successfully', [
        'file_id'      => $fileId,
        'file_type'    => $actualType,
        'file_name'    => $origName,
        'stored_path'  => $storedPath,
        'size_kb'      => $sizeKB,
        'submission_id'=> $submissionId, // return new id if auto-created
    ]);
} catch (PDOException $e) {
    @unlink($destPath);
    jsonResponse(false, 'Database error: ' . $e->getMessage());
}