<?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 folder creation permission
function hasCreateFolderPermission($role_id) {
    $permissions = [
        '1' => true, // Admin
        '2' => true, // General Manager
        '3' => true, // 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
if (!hasCreateFolderPermission($role_id)) {
    $_SESSION['error_message'] = "You don't have permission to create folders.";
    header('Location: file_manager.php');
    exit();
}

// 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
$folder_name = isset($_POST['folder_name']) ? trim($_POST['folder_name']) : '';
$parent_folder_id = isset($_POST['parent_folder_id']) && intval($_POST['parent_folder_id']) > 0 ? intval($_POST['parent_folder_id']) : null;
$related_file_number = isset($_POST['related_file_number']) ? trim($_POST['related_file_number']) : null;

// Validate folder name
if (empty($folder_name)) {
    $_SESSION['error_message'] = "Folder name is required.";
    header('Location: file_manager.php' . ($parent_folder_id ? '?folder_id=' . $parent_folder_id : ''));
    exit();
}

// Check if folder name already exists in the same parent
$check_sql = "SELECT folder_id FROM file_folders 
              WHERE folder_name = ? AND 
              " . ($parent_folder_id ? "parent_folder_id = ?" : "parent_folder_id IS NULL") . " AND
              is_deleted = 0";

$check_stmt = $conn->prepare($check_sql);

if ($parent_folder_id) {
    $check_stmt->bind_param("si", $folder_name, $parent_folder_id);
} else {
    $check_stmt->bind_param("s", $folder_name);
}

$check_stmt->execute();
$check_result = $check_stmt->get_result();

if ($check_result->num_rows > 0) {
    $_SESSION['error_message'] = "A folder with this name already exists in this location.";
    header('Location: file_manager.php' . ($parent_folder_id ? '?folder_id=' . $parent_folder_id : ''));
    exit();
}

$check_stmt->close();

// Check if parent folder exists
if ($parent_folder_id) {
    $parent_check_sql = "SELECT folder_id FROM file_folders WHERE folder_id = ? AND is_deleted = 0";
    $parent_check_stmt = $conn->prepare($parent_check_sql);
    $parent_check_stmt->bind_param("i", $parent_folder_id);
    $parent_check_stmt->execute();
    $parent_check_result = $parent_check_stmt->get_result();
    
    if ($parent_check_result->num_rows === 0) {
        $_SESSION['error_message'] = "Parent folder does not exist.";
        header('Location: file_manager.php');
        exit();
    }
    
    $parent_check_stmt->close();
}

// Check if related file number exists if provided
if (!empty($related_file_number)) {
    $file_number_check_sql = "SELECT file_number FROM files WHERE file_number = ?";
    $file_number_check_stmt = $conn->prepare($file_number_check_sql);
    $file_number_check_stmt->bind_param("s", $related_file_number);
    $file_number_check_stmt->execute();
    $file_number_check_result = $file_number_check_stmt->get_result();
    
    if ($file_number_check_result->num_rows === 0) {
        $related_file_number = null; // Reset to null if file number doesn't exist
    }
    
    $file_number_check_stmt->close();
}

// Create the folder in database
$insert_sql = "INSERT INTO file_folders (folder_name, parent_folder_id, created_by, related_file_number) 
               VALUES (?, ?, ?, ?)";

$insert_stmt = $conn->prepare($insert_sql);
$insert_stmt->bind_param("siis", $folder_name, $parent_folder_id, $user_id, $related_file_number);

if ($insert_stmt->execute()) {
    $folder_id = $insert_stmt->insert_id;
    
    // Log the folder creation
    $log_sql = "INSERT INTO file_access_logs (folder_id, user_id, access_type, ip_address) 
               VALUES (?, ?, 'edit', ?)";
    $log_stmt = $conn->prepare($log_sql);
    $access_type = 'edit';
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $log_stmt->bind_param("iis", $folder_id, $user_id, $ip_address);
    $log_stmt->execute();
    $log_stmt->close();
    
    $_SESSION['success_message'] = "Folder \"$folder_name\" created successfully.";
} else {
    $_SESSION['error_message'] = "Error creating folder: " . $insert_stmt->error;
}

$insert_stmt->close();
$conn->close();

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