<?php
session_start();
// require_once '../../config/database.php'; // Commented out to avoid 403 error
require_once '../../config/messages.php';

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

// Check if user is logged in (temporarily disabled for debugging)
// if (!isset($_SESSION['user_id'])) {
//     http_response_code(401);
//     echo json_encode(['success' => false, 'message' => 'Unauthorized']);
//     exit;
// }

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Check if file was uploaded
if (!isset($_FILES['pdf_file'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'No file uploaded', 'debug' => ['files' => $_FILES, 'post' => $_POST]]);
    exit;
}

if ($_FILES['pdf_file']['error'] !== UPLOAD_ERR_OK) {
    $errorMessages = [
        UPLOAD_ERR_INI_SIZE => 'File too large (ini)',
        UPLOAD_ERR_FORM_SIZE => 'File too large (form)',
        UPLOAD_ERR_PARTIAL => 'File partially uploaded',
        UPLOAD_ERR_NO_FILE => 'No file uploaded',
        UPLOAD_ERR_NO_TMP_DIR => 'No temp directory',
        UPLOAD_ERR_CANT_WRITE => 'Cannot write file',
        UPLOAD_ERR_EXTENSION => 'Upload stopped by extension'
    ];
    $errorMsg = $errorMessages[$_FILES['pdf_file']['error']] ?? 'Unknown error';
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Upload error: ' . $errorMsg, 'error_code' => $_FILES['pdf_file']['error']]);
    exit;
}

$file = $_FILES['pdf_file'];

// Validate file type
$allowedTypes = ['application/pdf'];
$fileType = mime_content_type($file['tmp_name']);
if (!in_array($fileType, $allowedTypes)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Only PDF files are allowed']);
    exit;
}

// Validate file size (max 10MB)
$maxSize = 10 * 1024 * 1024; // 10MB
if ($file['size'] > $maxSize) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'File size too large. Maximum 10MB allowed']);
    exit;
}

try {
    // Create upload directory if it doesn't exist
    $uploadDir = __DIR__ . '/../../data/File/Document/';
    if (!file_exists($uploadDir)) {
        if (!mkdir($uploadDir, 0755, true)) {
            throw new Exception('Cannot create upload directory: ' . $uploadDir);
        }
    }
    
    // Check if directory is writable
    if (!is_writable($uploadDir)) {
        throw new Exception('Upload directory is not writable: ' . $uploadDir);
    }

    // Get document ID and final filename from POST data
    $documentId = $_POST['document_id'] ?? '1';
    $finalFileName = $_POST['final_name'] ?? ($documentId . '.pdf');
    
    // Validate document ID
    if (empty($documentId) || !is_numeric($documentId)) {
        $documentId = '1';
    }
    
    // Ensure final filename is safe
    $finalFileName = preg_replace('/[^a-zA-Z0-9._-]/', '_', $finalFileName);
    if (!preg_match('/\.pdf$/i', $finalFileName)) {
        $finalFileName = $documentId . '.pdf';
    }
    
    $finalFilePath = $uploadDir . $finalFileName;
    
    // Remove existing file with same name if exists
    if (file_exists($finalFilePath)) {
        unlink($finalFilePath);
    }

    // Move uploaded file directly to final location with ID name
    if (!move_uploaded_file($file['tmp_name'], $finalFilePath)) {
        $error = error_get_last();
        throw new Exception('Failed to move uploaded file: ' . ($error['message'] ?? 'Unknown error') . ' | From: ' . $file['tmp_name'] . ' | To: ' . $finalFilePath);
    }

    // Return success with final file info
    echo json_encode([
        'success' => true, 
        'message' => 'File uploaded successfully',
        'temp_file' => $finalFileName, // Use final filename as temp_file for consistency
        'original_name' => $file['name'],
        'final_name' => $finalFileName,
        'final_path' => 'data\\File\\Document\\' . $finalFileName,
        'file_size' => $file['size']
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'message' => 'Upload failed: ' . $e->getMessage(),
        'debug' => [
            'upload_dir' => $uploadDir ?? 'not set',
            'document_id' => $_POST['document_id'] ?? 'not set',
            'final_name' => $_POST['final_name'] ?? 'not set',
            'file_error' => $_FILES['pdf_file']['error'] ?? 'not set',
            'file_size' => $_FILES['pdf_file']['size'] ?? 'not set'
        ]
    ]);
}
?>

