<?php
session_start();
include 'layouts/dbconn.php';

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

// Log received data for debugging
$debug_log = "Debug log - " . date('Y-m-d H:i:s') . "\n";
$debug_log .= "POST: " . print_r($_POST, true) . "\n";
$debug_log .= "FILES: " . print_r($_FILES, true) . "\n";
file_put_contents('upload_debug.log', $debug_log, FILE_APPEND);

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('HTTP/1.1 401 Unauthorized');
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

$user_id = $_SESSION['user_id'];

// Function to check if user has upload permission
function hasUploadPermission($role_id) {
    $permissions = [
        '1' => true, // Admin
        '2' => true, // General Manager
        '3' => true, // Operations
        '4' => true, // Finance
        '5' => true, // Declaration Officer
        '6' => false, // Shipping Line Clerk
        '7' => false, // Transport Supervisor
    ];
    
    return isset($permissions[$role_id]) ? $permissions[$role_id] : false;
}

// Get user role
$role_query = "SELECT role_id FROM users WHERE user_id = ?";
$role_stmt = $conn->prepare($role_query);
$role_stmt->bind_param("i", $user_id);
$role_stmt->execute();
$role_result = $role_stmt->get_result();

if ($role_result && $role_row = $role_result->fetch_assoc()) {
    $role_id = $role_row['role_id'];
} else {
    header('HTTP/1.1 400 Bad Request');
    echo json_encode(['error' => 'Invalid user']);
    exit();
}

$role_stmt->close();

// Check permission
if (!hasUploadPermission($role_id)) {
    header('HTTP/1.1 403 Forbidden');
    echo json_encode(['error' => 'Permission denied']);
    exit();
}

// Get form data
$folder_id = isset($_POST['folder_id']) && intval($_POST['folder_id']) > 0 ? intval($_POST['folder_id']) : null;
$description = isset($_POST['description']) ? trim($_POST['description']) : null;
$related_file_number = isset($_POST['related_file_number']) ? trim($_POST['related_file_number']) : null;

// Check if this is a multiple file upload or single
if (isset($_FILES['file']) && is_array($_FILES['file']['name'])) {
    // Multiple files
    $files = $_FILES['file'];
    $file_count = count($files['name']);
    $success_count = 0;
    $errors = [];

    for ($i = 0; $i < $file_count; $i++) {
        if ($files['error'][$i] === UPLOAD_ERR_OK) {
            // Process each file
            $result = processFileUpload(
                $files['name'][$i],
                $files['tmp_name'][$i],
                $files['size'][$i],
                $files['type'][$i],
                $folder_id,
                $description,
                $related_file_number,
                $user_id,
                $conn
            );
            
            if ($result['success']) {
                $success_count++;
            } else {
                $errors[] = $result['error'];
            }
        } else {
            $errors[] = getUploadErrorMessage($files['error'][$i]);
        }
    }
    
    if ($success_count > 0) {
        echo json_encode([
            'success' => true,
            'message' => "$success_count files uploaded successfully" . 
                        (count($errors) > 0 ? " with " . count($errors) . " errors" : "")
        ]);
    } else {
        header('HTTP/1.1 400 Bad Request');
        echo json_encode(['error' => implode("; ", $errors)]);
    }
} else {
    // Single file
    if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        header('HTTP/1.1 400 Bad Request');
        $error_message = "No file uploaded";
        if (isset($_FILES['file'])) {
            $error_message = getUploadErrorMessage($_FILES['file']['error']);
        }
        echo json_encode(['error' => $error_message]);
        exit();
    }
    
    $result = processFileUpload(
        $_FILES['file']['name'],
        $_FILES['file']['tmp_name'],
        $_FILES['file']['size'],
        $_FILES['file']['type'],
        $folder_id,
        $description,
        $related_file_number,
        $user_id,
        $conn
    );
    
    if ($result['success']) {
        echo json_encode([
            'success' => true,
            'file_id' => $result['file_id'],
            'message' => 'File uploaded successfully'
        ]);
    } else {
        header('HTTP/1.1 400 Bad Request');
        echo json_encode(['error' => $result['error']]);
    }
}

/**
 * Process a single file upload
 */
function processFileUpload($file_name, $tmp_name, $file_size, $file_type, $folder_id, $description, $related_file_number, $user_id, $conn) {
    // Get file extension
    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
    
    // Define allowed extensions
    $allowed_extensions = array('pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'csv', 'jpg', 'jpeg', 'png', 'gif', 'zip', 'rar');
    
    // Check if file extension is allowed
    if (!in_array($file_ext, $allowed_extensions)) {
        return ['success' => false, 'error' => "File type $file_ext not allowed"];
    }
    
    // Check file size (max 20MB)
    if ($file_size > 20971520) { // 20MB in bytes
        return ['success' => false, 'error' => 'File too large. Maximum size is 20MB'];
    }
    
    // Create upload directory if it doesn't exist
    $upload_dir = 'uploads/files';
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    // Create a unique filename to prevent overwriting
    $new_filename = uniqid('file_') . '_' . time() . '.' . $file_ext;
    $upload_path = $upload_dir . '/' . $new_filename;
    
    // Get file mime type
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $file_mime = finfo_file($finfo, $tmp_name);
    finfo_close($finfo);
    
    // Move the uploaded file
    if (move_uploaded_file($tmp_name, $upload_path)) {
        // Insert file info into database
        $insert_sql = "INSERT INTO file_manager (file_name, file_path, file_type, file_size, file_extension, 
                                              folder_id, uploaded_by, description, related_file_number) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $insert_stmt = $conn->prepare($insert_sql);
        $insert_stmt->bind_param("sssississ", 
                                $file_name,
                                $upload_path,
                                $file_mime,
                                $file_size,
                                $file_ext,
                                $folder_id,
                                $user_id,
                                $description,
                                $related_file_number);
        
        if ($insert_stmt->execute()) {
            $file_id = $insert_stmt->insert_id;
            
            // Log the upload action
            $log_sql = "INSERT INTO file_access_logs (file_id, user_id, access_type, ip_address) 
                       VALUES (?, ?, 'upload', ?)";
            $log_stmt = $conn->prepare($log_sql);
            $ip_address = $_SERVER['REMOTE_ADDR'];
            $log_stmt->bind_param("iis", $file_id, $user_id, $ip_address);
            $log_stmt->execute();
            $log_stmt->close();
            
            $insert_stmt->close();
            return ['success' => true, 'file_id' => $file_id];
        } else {
            // Database error
            $error = "Database error: " . $insert_stmt->error;
            $insert_stmt->close();
            
            // Remove the uploaded file since we couldn't record it in database
            unlink($upload_path);
            return ['success' => false, 'error' => $error];
        }
    } else {
        // File move failed
        return ['success' => false, 'error' => 'Failed to move uploaded file'];
    }
}

/**
 * Get meaningful error message for upload errors
 */
function getUploadErrorMessage($error_code) {
    $upload_errors = [
        UPLOAD_ERR_INI_SIZE => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
        UPLOAD_ERR_FORM_SIZE => 'The uploaded file exceeds the MAX_FILE_SIZE directive specified in the HTML form',
        UPLOAD_ERR_PARTIAL => 'The uploaded file was only partially uploaded',
        UPLOAD_ERR_NO_FILE => 'No file was uploaded',
        UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder',
        UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
        UPLOAD_ERR_EXTENSION => 'A PHP extension stopped the file upload'
    ];
    
    return isset($upload_errors[$error_code]) ? $upload_errors[$error_code] : 'Unknown upload error';
}
?>