<?php
/**
 * media_logic.php - Advanced File & Folder Management
 * /assets/files/ ফোল্ডারের ভেতর ফাইল এবং ফোল্ডার ম্যানেজমেন্ট সিস্টেম
 */

// ১. কনফিগারেশন এবং ডিরেক্টরি সেটআপ
$base_dir = 'assets/files/';
if (!file_exists($base_dir)) {
    mkdir($base_dir, 0777, true);
}

// বর্তমান পাথ নির্ধারণ (ব্রাউজ করার জন্য)
$current_path = isset($_GET['path']) ? $_GET['path'] : '';
$relative_path = str_replace(['..', './'], '', $current_path);
$target_dir = rtrim($base_dir . $relative_path, '/') . '/';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// রিকার্সিভলি ফোল্ডার কপি করার ফাংশন
function custom_copy($src, $dst) {
    if (is_dir($src)) {
        if (!file_exists($dst)) mkdir($dst, 0777, true);
        $files = scandir($src);
        foreach ($files as $file) {
            if ($file != "." && $file != "..") custom_copy("$src/$file", "$dst/$file");
        }
    } else {
        copy($src, $dst);
    }
}

// ২. লজিক হ্যান্ডলিং (Actions)

// ফোল্ডার তৈরি
if (isset($_POST['create_folder'])) {
    $folder_name = preg_replace('/[^a-zA-Z0-9_-]/', '', $_POST['folder_name']);
    if (!empty($folder_name)) {
        $new_folder_path = $target_dir . $folder_name;
        if (!file_exists($new_folder_path)) {
            mkdir($new_folder_path, 0777, true);
            $_SESSION['media_msg'] = 'folder_created';
        }
    }
    echo '<script>window.location.href="admin.php?view=media&path=' . urlencode($current_path) . '";</script>';
    exit();
}

// ফাইল আপলোড (নির্দিষ্ট ফোল্ডার অপশনসহ)
if (isset($_POST['upload_media'])) {
    $dest_folder = isset($_POST['target_upload_path']) ? $_POST['target_upload_path'] : $current_path;
    $upload_target = rtrim($base_dir . str_replace(['..', './'], '', $dest_folder), '/') . '/';
    
    if (isset($_FILES['media_file']) && $_FILES['media_file']['error'] == 0) {
        $file_name = $_FILES['media_file']['name'];
        $file_tmp = $_FILES['media_file']['tmp_name'];
        $safe_name = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '', $file_name);
        
        if (move_uploaded_file($file_tmp, $upload_target . $safe_name)) {
            $_SESSION['media_msg'] = 'success';
        } else {
            $_SESSION['media_msg'] = 'failed';
        }
    }
    echo '<script>window.location.href="admin.php?view=media&path=' . urlencode($dest_folder) . '";</script>';
    exit();
}

// ডিলিট লজিক
if (isset($_GET['delete'])) {
    $item = basename($_GET['delete']);
    $full_path = $target_dir . $item;
    if (file_exists($full_path)) {
        if (is_dir($full_path)) {
            $files_in_dir = array_diff(scandir($full_path), array('.', '..'));
            if (empty($files_in_dir)) {
                rmdir($full_path);
                $_SESSION['media_msg'] = 'deleted';
            } else {
                $_SESSION['media_msg'] = 'folder_not_empty';
            }
        } else {
            unlink($full_path);
            $_SESSION['media_msg'] = 'deleted';
        }
    }
    echo '<script>window.location.href="admin.php?view=media&path=' . urlencode($current_path) . '";</script>';
    exit();
}

// রিনেম লজিক
if (isset($_POST['rename_item'])) {
    $old_name = basename($_POST['old_name']);
    $new_name = preg_replace('/[^a-zA-Z0-9._-]/', '', $_POST['new_name']);
    if (file_exists($target_dir . $old_name) && !empty($new_name)) {
        rename($target_dir . $old_name, $target_dir . $new_name);
        $_SESSION['media_msg'] = 'renamed';
    }
    echo '<script>window.location.href="admin.php?view=media&path=' . urlencode($current_path) . '";</script>';
    exit();
}

// কপি ও মুভ লজিক
if (isset($_POST['move_copy_item'])) {
    $item_name = $_POST['item_name'];
    $action = $_POST['action_type']; // 'move' or 'copy'
    $target_subpath = $_POST['target_subpath'];
    
    $source = $target_dir . $item_name;
    $dest = rtrim($base_dir . str_replace(['..', './'], '', $target_subpath), '/') . '/' . $item_name;

    if (file_exists($source)) {
        if ($action == 'move') {
            rename($source, $dest);
            $_SESSION['media_msg'] = 'moved';
        } else {
            custom_copy($source, $dest);
            $_SESSION['media_msg'] = 'copied';
        }
    }
    echo '<script>window.location.href="admin.php?view=media&path=' . urlencode($current_path) . '";</script>';
    exit();
}

// ৩. ফাইল ও ফোল্ডার তালিকা তৈরি
$items = @scandir($target_dir) ?: [];
$items = array_diff($items, array('.', '..'));
$folders = [];
$files = [];
foreach ($items as $item) {
    if (is_dir($target_dir . $item)) $folders[] = $item;
    else $files[] = $item;
}

// গ্লোবাল সার্চের জন্য রিকার্সিভলি সব ফাইল ও ফোল্ডার খুঁজে বের করার ফাংশন (শুধুমাত্র Root এর জন্য)
function get_recursive_items($dir, $base_dir) {
    $results = [];
    $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
    foreach (new RecursiveIteratorIterator($it, RecursiveIteratorIterator::SELF_FIRST) as $file) {
        $fullPath = $file->getRealPath();
        $relativePath = str_replace(realpath($base_dir) . DIRECTORY_SEPARATOR, '', $fullPath);
        $relativePath = str_replace(DIRECTORY_SEPARATOR, '/', $relativePath);
        $name = basename($relativePath);
        $results[] = [
            'name' => $name,
            'is_dir' => is_dir($fullPath),
            'rel_path' => $relativePath,
            'full_url' => $relativePath
        ];
    }
    return $results;
}

// ড্রপডাউনের জন্য সকল সাব-ফোল্ডার লিস্ট তৈরির ফাংশন
function get_all_folders($dir, $base_prefix = '') {
    $list = [];
    $items = is_dir($dir) ? array_diff(scandir($dir), array('.', '..')) : [];
    foreach ($items as $item) {
        if (is_dir($dir . '/' . $item)) {
            $path = ($base_prefix ? $base_prefix . '/' : '') . $item;
            $list[] = $path;
            $list = array_merge($list, get_all_folders($dir . '/' . $item, $path));
        }
    }
    return $list;
}
$all_folder_list = array_merge([''], get_all_folders($base_dir));

function getFileIcon($ext) {
    $icons = [
        'pdf' => 'fa-file-pdf', 'doc' => 'fa-file-word', 'docx' => 'fa-file-word',
        'xls' => 'fa-file-excel', 'xlsx' => 'fa-file-excel', 'zip' => 'fa-file-archive',
        'rar' => 'fa-file-archive', 'mp3' => 'fa-file-audio', 'mp4' => 'fa-file-video'
    ];
    return isset($icons[$ext]) ? $icons[$ext] : 'fa-file';
}

// ৪. মেসেজ অ্যালার্ট
$alert_msg = '';
if (isset($_SESSION['media_msg'])) {
    $m = $_SESSION['media_msg'];
    $msgs = [
        'success' => 'ফাইল আপলোড হয়েছে!', 'deleted' => 'ডিলিট করা হয়েছে।',
        'folder_created' => 'ফোল্ডার তৈরি হয়েছে!', 'renamed' => 'রিনেম করা হয়েছে।',
        'moved' => 'সফলভাবে মুভ করা হয়েছে!', 'copied' => 'সফলভাবে কপি করা হয়েছে!',
        'folder_not_empty' => 'ফোল্ডারটি খালি নয়!'
    ];
    $type = ($m == 'folder_not_empty' || $m == 'failed') ? 'error' : ($m == 'deleted' ? 'info' : 'success');
    $alert_msg = isset($msgs[$m]) ? '<div class="alert '.$type.'">'.$msgs[$m].'</div>' : '';
    unset($_SESSION['media_msg']);
}

// ৫. সার্চের জন্য ডেটা প্রস্তুত করা (শুধুমাত্র Root এ থাকলে গ্লোবাল সার্চ ডেটা পাস হবে)
$is_root = ($current_path === '');
$search_data = [];
if ($is_root) {
    $search_data = get_recursive_items($base_dir, $base_dir);
}
?>

<style>
    .media-container { font-family: 'Segoe UI', sans-serif; padding: 0px; min-height: 100vh; }
    .top-bar { background: white; padding: 10px 20px; border-radius: 12px; display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 15px; margin-bottom: 10px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
    .breadcrumb { font-size: 13px; color: #64748b; margin-bottom: 20px; display: flex; align-items: center; gap: 5px; background: #fff; padding: 8px 15px; border-radius: 8px; border: 1px solid #e2e8f0; }
    .breadcrumb a { color: #2563eb; text-decoration: none; font-weight: 600; }
    .alert { padding: 12px 20px; border-radius: 8px; margin-bottom: 15px; font-size: 14px; }
    .success { background: #dcfce7; color: #166534; }
    .error { background: #fee2e2; color: #991b1b; }
    .info { background: #e0f2fe; color: #075985; }
    .action-forms { display: flex; gap: 10px; flex-wrap: wrap; }
    .input-group { display: flex; border: 1px solid #e2e8f0; border-radius: 6px; overflow: hidden; background: white; }
    .input-group select, .input-group input { border: none; padding: 8px 12px; outline: none; font-size: 13px; }
    .btn-action { background: #2563eb; color: white; border: none; padding: 8px 15px; cursor: pointer; font-size: 13px; font-weight: 600; }
    .media-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 20px; }
    .item-card { background: white; border-radius: 10px; border: 1px solid #e2e8f0; transition: 0.3s; position: relative; text-align: center; overflow: hidden; }
    .item-card:hover { transform: translateY(-3px); box-shadow: 0 10px 15px rgba(0,0,0,0.05); }
    .item-preview { height: 75px; display: flex; align-items: center; justify-content: center; background: #f8fafc; font-size: 40px; }
    .item-preview img { width: 100%; height: 100%; object-fit: cover; }
    .folder-icon { color: #facc15; }
    .item-info { padding: 0px 5px; }
    .item-name { font-size: 12px; font-weight: 600; color: #334155; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-bottom: 8px; }
    .item-actions { display: flex; justify-content: center; gap: 5px; opacity: 0; transition: 0.3s; padding-bottom: 10px; }
    .item-card:hover .item-actions { opacity: 1; }
    .act-btn { width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; border-radius: 4px; background: #f1f5f9; color: #475569; text-decoration: none; font-size: 11px; border: none; cursor: pointer; }
    .act-btn:hover { background: #e2e8f0; color: #1e293b; }
    .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; align-items: center; justify-content: center; }
    .modal-content { background: white; padding: 20px; border-radius: 10px; width: 320px; box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1); }
    
    /* Search Bar Specific */
    .search-wrapper { position: relative; flex: 1; min-width: 250px; }
    .search-wrapper i { position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #94a3b8; font-size: 14px; }
    .search-input { width: 80%; padding: 10px 15px 10px 35px; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 13px; outline: none; transition: 0.2s; }
    .search-input:focus { border-color: #2563eb; box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1); }
    .search-results-overlay { display: none; background: white; border-radius: 12px; padding: 20px; margin-top: 10px; border: 1px solid #e2e8f0; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); }
</style>

<div class="media-container">
    <div class="top-bar">
        <!-- Search Bar -->
        <div class="search-wrapper">
            <i class="fas fa-search"></i>
            <input type="text" id="mediaSearch" class="search-input" placeholder="<?php echo $is_root ? 'সব ফোল্ডারে সার্চ করুন...' : 'এই ফোল্ডারে সার্চ করুন...'; ?>" onkeyup="handleSearch()">
        </div>

        <form method="POST" class="input-group">
            <input type="text" name="folder_name" placeholder="নতুন ফোল্ডার..." required>
            <button type="submit" name="create_folder" class="btn-action" style="background:#64748b;"><i class="fas fa-folder-plus"></i></button>
        </form>

        <form method="POST" enctype="multipart/form-data" class="action-forms">
            <div class="input-group">
                <select name="target_upload_path">
                    <?php foreach($all_folder_list as $f): ?>
                        <option value="<?php echo $f; ?>" <?php echo ($f == $current_path) ? 'selected' : ''; ?>>
                            <?php echo $f === '' ? 'Root' : $f; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <input type="file" name="media_file" required>
                <button type="submit" name="upload_media" class="btn-action"><i class="fas fa-upload"></i> আপলোড</button>
            </div>
        </form>
    </div>

    <!-- Breadcrumb -->
    <div class="breadcrumb">
        <i class="fas fa-home"></i> <a href="admin.php?view=media">Home</a>
        <?php 
        $cum_path = '';
        foreach (explode('/', $current_path) as $part) {
            if ($part) {
                $cum_path .= $part . '/';
                echo ' / <a href="admin.php?view=media&path='.urlencode(rtrim($cum_path, '/')).'">'.$part.'</a>';
            }
        }
        ?>
        <span id="searchStatus" style="margin-left:auto; display:none; color:#2563eb; font-weight:bold;">সার্চ রেজাল্ট দেখানো হচ্ছে...</span>
    </div>

    <?php echo $alert_msg; ?>

    <!-- Search Results View (Root এর জন্য গ্লোবাল সার্চের সময় ব্যবহৃত হবে) -->
    <div id="globalResultsGrid" class="media-grid" style="display:none; margin-bottom:40px;"></div>

    <!-- মেইন গ্রিড -->
    <div class="media-grid" id="mediaGrid">
        <?php foreach (array_merge($folders, $files) as $item): 
            $is_dir = is_dir($target_dir . $item);
            $ext = $is_dir ? '' : strtolower(pathinfo($item, PATHINFO_EXTENSION));
            $file_url = $target_dir . $item;
        ?>
            <div class="item-card" data-name="<?php echo strtolower($item); ?>">
                <?php if($is_dir): ?>
                    <a href="admin.php?view=media&path=<?php echo urlencode(($current_path ? $current_path.'/' : '').$item); ?>" style="text-decoration:none;">
                        <div class="item-preview"><i class="fas fa-folder folder-icon"></i></div>
                    </a>
                <?php else: ?>
                    <div class="item-preview">
                        <?php if(in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp'])): ?>
                            <img src="<?php echo $file_url; ?>" loading="lazy">
                        <?php else: ?>
                            <i class="fas <?php echo getFileIcon($ext); ?>" style="color:#94a3b8"></i>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
                
                <div class="item-info">
                    <div class="item-name" title="<?php echo $item; ?>"><?php echo $item; ?></div>
                    <div class="item-actions">
                        <?php if(!$is_dir): ?>
                            <button onclick="copyLink('<?php echo (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]/" . $file_url; ?>')" class="act-btn"><i class="fas fa-link"></i></button>
                        <?php endif; ?>
                        <button onclick="openMoveCopyModal('<?php echo $item; ?>')" class="act-btn" title="মুভ/কপি"><i class="fas fa-exchange-alt"></i></button>
                        <button onclick="openRenameModal('<?php echo $item; ?>')" class="act-btn"><i class="fas fa-edit"></i></button>
                        <a href="admin.php?view=media&path=<?php echo urlencode($current_path); ?>&delete=<?php echo urlencode($item); ?>" class="act-btn" onclick="return confirm('ডিলিট নিশ্চিত?')" style="color:#ef4444"><i class="fas fa-trash"></i></a>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- রিনেম মডাল -->
<div id="renameModal" class="modal">
    <div class="modal-content">
        <form method="POST">
            <h4 style="margin:0 0 15px 0">রিনেম করুন</h4>
            <input type="hidden" name="old_name" id="old_name_input">
            <input type="text" name="new_name" id="new_name_input" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px; margin-bottom:15px;" required>
            <div style="text-align:right">
                <button type="button" onclick="closeModals()" style="background:none; border:none; cursor:pointer">বাতিল</button>
                <button type="submit" name="rename_item" class="btn-action" style="border-radius:4px">সেভ</button>
            </div>
        </form>
    </div>
</div>

<!-- মুভ/কপি মডাল -->
<div id="moveCopyModal" class="modal">
    <div class="modal-content">
        <form method="POST">
            <h4 style="margin:0 0 15px 0">মুভ বা কপি করুন</h4>
            <input type="hidden" name="item_name" id="move_item_name">
            <div style="margin-bottom:10px">
                <label style="font-size:12px">অ্যাকশন:</label>
                <select name="action_type" style="width:100%; padding:8px; border-radius:4px">
                    <option value="move">Move (মুভ)</option>
                    <option value="copy">Copy (কপি)</option>
                </select>
            </div>
            <div style="margin-bottom:15px">
                <label style="font-size:12px">টার্গেট ফোল্ডার:</label>
                <select name="target_subpath" style="width:100%; padding:8px; border-radius:4px">
                    <?php foreach($all_folder_list as $f): ?>
                        <option value="<?php echo $f; ?>"><?php echo $f===''?'Root':$f;?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div style="text-align:right">
                <button type="button" onclick="closeModals()" style="background:none; border:none; cursor:pointer">বাতিল</button>
                <button type="submit" name="move_copy_item" class="btn-action" style="border-radius:4px">সম্পন্ন করুন</button>
            </div>
        </form>
    </div>
</div>

<script>
// PHP থেকে পাওয়া গ্লোবাল ডাটা
const globalSearchItems = <?php echo json_encode($search_data); ?>;
const isRoot = <?php echo $is_root ? 'true' : 'false'; ?>;
const baseDir = '<?php echo $base_dir; ?>';

function handleSearch() {
    let input = document.getElementById('mediaSearch').value.toLowerCase().trim();
    let mediaGrid = document.getElementById('mediaGrid');
    let globalGrid = document.getElementById('globalResultsGrid');
    let searchStatus = document.getElementById('searchStatus');

    if (input === "") {
        mediaGrid.style.display = "grid";
        globalGrid.style.display = "none";
        searchStatus.style.display = "none";
        filterLocalMedia(""); // Reset local filter
        return;
    }

    if (isRoot) {
        // Root এ থাকলে গ্লোবাল সার্চ
        mediaGrid.style.display = "none";
        globalGrid.style.display = "grid";
        searchStatus.style.display = "inline";
        renderGlobalResults(input);
    } else {
        // সাব-ফোল্ডারে থাকলে শুধুমাত্র লোকাল ফিল্টার
        filterLocalMedia(input);
    }
}

function filterLocalMedia(input) {
    let cards = document.querySelectorAll('#mediaGrid .item-card');
    cards.forEach(card => {
        let name = card.getAttribute('data-name');
        card.style.display = name.includes(input) ? "" : "none";
    });
}

function renderGlobalResults(query) {
    let globalGrid = document.getElementById('globalResultsGrid');
    globalGrid.innerHTML = "";
    
    let filtered = globalSearchItems.filter(item => item.name.toLowerCase().includes(query));

    if (filtered.length === 0) {
        globalGrid.innerHTML = `<div style="grid-column:1/-1; padding:40px; text-align:center; color:#64748b;">কোনো রেজাল্ট পাওয়া যায়নি।</div>`;
        return;
    }

    filtered.forEach(item => {
        let card = document.createElement('div');
        card.className = "item-card";
        
        let iconHtml = "";
        let url = `admin.php?view=media&path=${encodeURIComponent(item.rel_path)}`;
        
        if (item.is_dir) {
            iconHtml = `<a href="${url}" style="text-decoration:none;"><div class="item-preview"><i class="fas fa-folder folder-icon"></i></div></a>`;
        } else {
            let ext = item.name.split('.').pop().toLowerCase();
            let fullFileUrl = baseDir + item.rel_path;
            if(['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(ext)) {
                iconHtml = `<div class="item-preview"><img src="${fullFileUrl}" loading="lazy"></div>`;
            } else {
                iconHtml = `<div class="item-preview"><i class="fas fa-file" style="color:#94a3b8"></i></div>`;
            }
        }

        card.innerHTML = `
            ${iconHtml}
            <div class="item-info">
                <div class="item-name" title="${item.name}">${item.name}</div>
                <div style="font-size:10px; color:#94a3b8; margin-bottom:5px;">In: ${item.rel_path.split('/').slice(0,-1).join('/') || 'Root'}</div>
                <div class="item-actions">
                     <a href="${item.is_dir ? url : 'admin.php?view=media&path=' + encodeURIComponent(item.rel_path.split('/').slice(0,-1).join('/'))}" class="act-btn" title="ফোল্ডারে যান"><i class="fas fa-external-link-alt"></i></a>
                </div>
            </div>
        `;
        globalGrid.appendChild(card);
    });
}

function openRenameModal(n) { document.getElementById('old_name_input').value=n; document.getElementById('new_name_input').value=n; document.getElementById('renameModal').style.display='flex'; }
function openMoveCopyModal(n) { document.getElementById('move_item_name').value=n; document.getElementById('moveCopyModal').style.display='flex'; }
function closeModals() { document.getElementById('renameModal').style.display='none'; document.getElementById('moveCopyModal').style.display='none'; }
function copyLink(u) { navigator.clipboard.writeText(u); alert('লিঙ্ক কপি হয়েছে!'); }
</script>