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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    $_SESSION['error_message'] = "Please log in to continue.";
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Function to check if user has delete permission
function hasDeletePermission($role_id) {
    $permissions = [
        '1' => true, // Admin
        '2' => false, // General Manager
        '3' => false, // Operations
        '4' => false, // Finance
        '5' => false, // 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 {
    $_SESSION['error_message'] = "Error retrieving user information.";
    header('Location: file_manager.php');
    exit();
}

$role_stmt->close();

// Check permission - admins can delete anything, other users can only delete their own files
$is_admin = hasDeletePermission($role_id);

// Check if form was submitted
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error_message'] = "Invalid request method.";
    header('Location: file_manager.php');
    exit();
}

// Get form data
$item_id = isset($_POST['item_id']) ? intval($_POST['item_id']) : 0;
$item_type = isset($_POST['item_type']) ? $_POST['item_type'] : '';
$return_folder = isset($_POST['return_folder']) ? intval($_POST['return_folder']) : 0;

// Validate item type
if ($item_type !== 'file' && $item_type !== 'folder') {
    $_SESSION['error_message'] = "Invalid item type.";
    header('Location: file_manager.php' . ($return_folder ? '?folder_id=' . $return_folder : ''));
    exit();
}

// Validate item ID
if (empty($item_id)) {
    $_SESSION['error_message'] = "No item specified for deletion.";
    header('Location: file_manager.php' . ($return_folder ? '?folder_id=' . $return_folder : ''));
    exit();
}

// Check ownership if not admin
if (!$is_admin) {
    if ($item_type === 'file') {
        $ownership_sql = "SELECT uploaded_by FROM file_manager WHERE file_id = ?";
        $ownership_stmt = $conn->prepare($ownership_sql);
        $ownership_stmt->bind_param("i", $item_id);
        $ownership_stmt->execute();
        $ownership_result = $ownership_stmt->get_result();
        
        if ($ownership_result->num_rows === 0) {
            $_SESSION['error_message'] = "File not found.";
            header('Location: file_manager.php' . ($return_folder ? '?folder_id=' . $return_folder : ''));
            exit();
        }
        
        $ownership = $ownership_result->fetch_assoc();
        if ($ownership['uploaded_by'] != $user_id) {
            $_SESSION['error_message'] = "You can only delete your own files.";
            header('Location: file_manager.php' . ($return_folder ? '?folder_id=' . $return_folder : ''));
            exit();
        }
        
        $ownership_stmt->close();
    } else { // folder
        $ownership_sql = "SELECT created_by FROM file_folders WHERE folder_id = ?";
        $ownership_stmt = $conn->prepare($ownership_sql);
        $ownership_stmt->bind_param("i", $item_id);
        $ownership_stmt->execute();
        $ownership_result = $ownership_stmt->get_result();
        
        if ($ownership_result->num_rows === 0) {
            $_SESSION['error_message'] = "Folder not found.";
            header('Location: file_manager.php' . ($return_folder ? '?folder_id=' . $return_folder : ''));
            exit();
        }
        
        $ownership = $ownership_result->fetch_assoc();
        if ($ownership['created_by'] != $user_id) {
            $_SESSION['error_message'] = "You can only delete your own folders.";
            header('Location: file_manager.php' . ($return_folder ? '?folder_id=' . $return_folder : ''));
            exit();
        }
        
        $ownership_stmt->close();
    }
}

// Start transaction
$conn->begin_transaction();

try {
    if ($item_type === 'file') {
        // Mark file as deleted in database (soft delete)
        $delete_sql = "UPDATE file_manager SET is_deleted = 1 WHERE file_id = ?";
        $delete_stmt = $conn->prepare($delete_sql);
        $delete_stmt->bind_param("i", $item_id);
        
        if (!$delete_stmt->execute()) {
            throw new Exception("Error deleting file: " . $delete_stmt->error);
        }
        
        $delete_stmt->close();
        
        // Log the deletion
        $log_sql = "INSERT INTO file_access_logs (file_id, user_id, access_type, ip_address) 
                   VALUES (?, ?, 'delete', ?)";
        $log_stmt = $conn->prepare($log_sql);
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $log_stmt->bind_param("iis", $item_id, $user_id, $ip_address);
        
        if (!$log_stmt->execute()) {
            throw new Exception("Error logging deletion: " . $log_stmt->error);
        }
        
        $log_stmt->close();
        
        $_SESSION['success_message'] = "File deleted successfully.";
    } else { // folder
        // Check if folder has any children
        $children_sql = "SELECT folder_id FROM file_folders WHERE parent_folder_id = ? AND is_deleted = 0";
        $children_stmt = $conn->prepare($children_sql);
        $children_stmt->bind_param("i", $item_id);
        $children_stmt->execute();
        $children_result = $children_stmt->get_result();
        
        $has_children = ($children_result->num_rows > 0);
        $children_stmt->close();
        
        // Check if folder has any files
        $files_sql = "SELECT file_id FROM file_manager WHERE folder_id = ? AND is_deleted = 0";
        $files_stmt = $conn->prepare($files_sql);
        $files_stmt->bind_param("i", $item_id);
        $files_stmt->execute();
        $files_result = $files_stmt->get_result();
        
        $has_files = ($files_result->num_rows > 0);
        $files_stmt->close();
        
        // If folder has children or files, recursively mark them as deleted
        if ($has_children) {
            // Function to recursively mark all subfolders and files as deleted
            function deleteFolder($conn, $folder_id, $user_id) {
                // Mark folder as deleted
                $folder_sql = "UPDATE file_folders SET is_deleted = 1 WHERE folder_id = ?";
                $folder_stmt = $conn->prepare($folder_sql);
                $folder_stmt->bind_param("i", $folder_id);
                $folder_stmt->execute();
                $folder_stmt->close();
                
                // Log folder deletion
                $log_sql = "INSERT INTO file_access_logs (folder_id, user_id, access_type, ip_address) 
                           VALUES (?, ?, 'delete', ?)";
                $log_stmt = $conn->prepare($log_sql);
                $ip_address = $_SERVER['REMOTE_ADDR'];
                $log_stmt->bind_param("iis", $folder_id, $user_id, $ip_address);
                $log_stmt->execute();
                $log_stmt->close();
                
                // Mark all files in this folder as deleted
                $files_sql = "UPDATE file_manager SET is_deleted = 1 WHERE folder_id = ?";
                $files_stmt = $conn->prepare($files_sql);
                $files_stmt->bind_param("i", $folder_id);
                $files_stmt->execute();
                $files_stmt->close();
                
                // Log file deletions
                $file_ids_sql = "SELECT file_id FROM file_manager WHERE folder_id = ?";
                $file_ids_stmt = $conn->prepare($file_ids_sql);
                $file_ids_stmt->bind_param("i", $folder_id);
                $file_ids_stmt->execute();
                $file_ids_result = $file_ids_stmt->get_result();
                
                while ($file = $file_ids_result->fetch_assoc()) {
                    $log_file_sql = "INSERT INTO file_access_logs (file_id, user_id, access_type, ip_address) 
                                   VALUES (?, ?, 'delete', ?)";
                    $log_file_stmt = $conn->prepare($log_file_sql);
                    $log_file_stmt->bind_param("iis", $file['file_id'], $user_id, $ip_address);
                    $log_file_stmt->execute();
                    $log_file_stmt->close();
                }
                
                $file_ids_stmt->close();
                
                // Find all subfolders
                $subfolders_sql = "SELECT folder_id FROM file_folders WHERE parent_folder_id = ?";
                $subfolders_stmt = $conn->prepare($subfolders_sql);
                $subfolders_stmt->bind_param("i", $folder_id);
                $subfolders_stmt->execute();
                $subfolders_result = $subfolders_stmt->get_result();
                
                // Recursively delete subfolders
                while ($subfolder = $subfolders_result->fetch_assoc()) {
                    deleteFolder($conn, $subfolder['folder_id'], $user_id);
                }
                
                $subfolders_stmt->close();
            }
            
            // Start recursive deletion
            deleteFolder($conn, $item_id, $user_id);
        } else {
            // Just mark this folder as deleted
            $delete_sql = "UPDATE file_folders SET is_deleted = 1 WHERE folder_id = ?";
            $delete_stmt = $conn->prepare($delete_sql);
            $delete_stmt->bind_param("i", $item_id);
            
            if (!$delete_stmt->execute()) {
                throw new Exception("Error deleting folder: " . $delete_stmt->error);
            }
            
            $delete_stmt->close();
            
            // Mark all files in this folder as deleted
            if ($has_files) {
                $mark_files_sql = "UPDATE file_manager SET is_deleted = 1 WHERE folder_id = ?";
                $mark_files_stmt = $conn->prepare($mark_files_sql);
                $mark_files_stmt->bind_param("i", $item_id);
                
                if (!$mark_files_stmt->execute()) {
                    throw new Exception("Error marking files as deleted: " . $mark_files_stmt->error);
                }
                
                $mark_files_stmt->close();
                
                // Log file deletions
                while ($file = $files_result->fetch_assoc()) {
                    $log_file_sql = "INSERT INTO file_access_logs (file_id, user_id, access_type, ip_address) 
                                   VALUES (?, ?, 'delete', ?)";
                    $log_file_stmt = $conn->prepare($log_file_sql);
                    $ip_address = $_SERVER['REMOTE_ADDR'];
                    $log_file_stmt->bind_param("iis", $file['file_id'], $user_id, $ip_address);
                    $log_file_stmt->execute();
                    $log_file_stmt->close();
                }
            }
            
            // Log the folder deletion
            $log_sql = "INSERT INTO file_access_logs (folder_id, user_id, access_type, ip_address) 
                       VALUES (?, ?, 'delete', ?)";
            $log_stmt = $conn->prepare($log_sql);
            $ip_address = $_SERVER['REMOTE_ADDR'];
            $log_stmt->bind_param("iis", $item_id, $user_id, $ip_address);
            
            if (!$log_stmt->execute()) {
                throw new Exception("Error logging deletion: " . $log_stmt->error);
            }
            
            $log_stmt->close();
        }
        
        $_SESSION['success_message'] = "Folder and its contents deleted successfully.";
    }
    
    // Commit the transaction
    $conn->commit();
} catch (Exception $e) {
    // Rollback on error
    $conn->rollback();
    $_SESSION['error_message'] = $e->getMessage();
}

// Close connection
$conn->close();

// Redirect back to file manager
header('Location: file_manager.php' . ($return_folder ? '?folder_id=' . $return_folder : ''));
exit();
?>