<?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 sharing permission
function hasSharingPermission($role_id) {
    $permissions = [
        '1' => true, // Admin
        '2' => true, // 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
if (!hasSharingPermission($role_id)) {
    $_SESSION['error_message'] = "You don't have permission to share files or 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
$file_id = isset($_POST['file_id']) && !empty($_POST['file_id']) ? intval($_POST['file_id']) : null;
$folder_id = isset($_POST['folder_id']) && !empty($_POST['folder_id']) ? intval($_POST['folder_id']) : null;
$share_type = isset($_POST['share_type']) ? $_POST['share_type'] : '';
$shared_with = isset($_POST['shared_with']) ? intval($_POST['shared_with']) : 0;
$permission_level = isset($_POST['permission_level']) ? $_POST['permission_level'] : 'read';
$expire_date = isset($_POST['expire_date']) && !empty($_POST['expire_date']) ? $_POST['expire_date'] : null;

// Validate we have either file_id or folder_id
if ($share_type !== 'file' && $share_type !== 'folder') {
    $_SESSION['error_message'] = "Invalid share type.";
    header('Location: file_manager.php');
    exit();
}

if ($share_type === 'file' && empty($file_id)) {
    $_SESSION['error_message'] = "No file specified for sharing.";
    header('Location: file_manager.php');
    exit();
}

if ($share_type === 'folder' && empty($folder_id)) {
    $_SESSION['error_message'] = "No folder specified for sharing.";
    header('Location: file_manager.php');
    exit();
}

// Validate shared_with user
if (empty($shared_with)) {
    $_SESSION['error_message'] = "Please select a user to share with.";
    header('Location: file_manager.php');
    exit();
}

// Check that user isn't sharing with themselves
if ($shared_with == $user_id) {
    $_SESSION['error_message'] = "You cannot share with yourself.";
    header('Location: file_manager.php');
    exit();
}

// Validate permission level
$valid_permissions = ['read', 'edit', 'delete'];
if (!in_array($permission_level, $valid_permissions)) {
    $permission_level = 'read'; // Default to read if invalid
}

// Get the return folder ID (for redirect)
$return_folder = 0;
if ($share_type === 'file' && !empty($file_id)) {
    $folder_query = "SELECT folder_id FROM file_manager WHERE file_id = ?";
    $folder_stmt = $conn->prepare($folder_query);
    $folder_stmt->bind_param("i", $file_id);
    $folder_stmt->execute();
    $folder_result = $folder_stmt->get_result();
    
    if ($folder_result && $folder_row = $folder_result->fetch_assoc()) {
        $return_folder = $folder_row['folder_id'];
    }
    
    $folder_stmt->close();
} elseif ($share_type === 'folder' && !empty($folder_id)) {
    $parent_query = "SELECT parent_folder_id FROM file_folders WHERE folder_id = ?";
    $parent_stmt = $conn->prepare($parent_query);
    $parent_stmt->bind_param("i", $folder_id);
    $parent_stmt->execute();
    $parent_result = $parent_stmt->get_result();
    
    if ($parent_result && $parent_row = $parent_result->fetch_assoc()) {
        $return_folder = $parent_row['parent_folder_id'] ?: 0;
    }
    
    $parent_stmt->close();
}

// Format expire date for MySQL
if ($expire_date) {
    $expire_date = date('Y-m-d H:i:s', strtotime($expire_date));
}

// Check if this share already exists and update it, or create a new one
$check_sql = "SELECT share_id FROM file_shares 
              WHERE " . ($share_type === 'file' ? "file_id = ?" : "folder_id = ?") . " 
              AND shared_with = ?";

$check_stmt = $conn->prepare($check_sql);
$check_id = $share_type === 'file' ? $file_id : $folder_id;
$check_stmt->bind_param("ii", $check_id, $shared_with);
$check_stmt->execute();
$check_result = $check_stmt->get_result();

if ($check_result->num_rows > 0) {
    // Update existing share
    $share = $check_result->fetch_assoc();
    $share_id = $share['share_id'];
    
    $update_sql = "UPDATE file_shares SET 
                  permission_level = ?, 
                  expire_date = ?, 
                  is_active = 1,
                  shared_by = ?
                  WHERE share_id = ?";
                  
    $update_stmt = $conn->prepare($update_sql);
    $update_stmt->bind_param("ssii", $permission_level, $expire_date, $user_id, $share_id);
    
    if ($update_stmt->execute()) {
        $_SESSION['success_message'] = "Sharing permissions updated successfully.";
    } else {
        $_SESSION['error_message'] = "Error updating sharing permissions: " . $update_stmt->error;
    }
    
    $update_stmt->close();
} else {
    // Create new share
    $insert_sql = "INSERT INTO file_shares (file_id, folder_id, shared_with, shared_by, permission_level, expire_date) 
                  VALUES (?, ?, ?, ?, ?, ?)";
    
    $insert_stmt = $conn->prepare($insert_sql);
    $file_id_param = $share_type === 'file' ? $file_id : null;
    $folder_id_param = $share_type === 'folder' ? $folder_id : null;
    $insert_stmt->bind_param("iiiiss", $file_id_param, $folder_id_param, $shared_with, $user_id, $permission_level, $expire_date);
    
    if ($insert_stmt->execute()) {
        // Log the share action
        $log_sql = "INSERT INTO file_access_logs (file_id, folder_id, user_id, access_type, ip_address) 
                   VALUES (?, ?, ?, 'share', ?)";
        $log_stmt = $conn->prepare($log_sql);
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $log_stmt->bind_param("iiis", $file_id_param, $folder_id_param, $user_id, $ip_address);
        $log_stmt->execute();
        $log_stmt->close();
        
        $_SESSION['success_message'] = "Item shared successfully.";
    } else {
        $_SESSION['error_message'] = "Error sharing item: " . $insert_stmt->error;
    }
    
    $insert_stmt->close();
}

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

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