<?php

// Include the DirectoryLister class
require_once('resources/DirectoryLister.php');

// Initialize the DirectoryLister object
// ... require_once('resources/DirectoryLister.php');

function encode_path($p)
{
    return implode('/', array_map('rawurlencode', explode('/', trim($p, '/'))));
}

// اگر پارامتر dir نیست ولی URL به یک دایرکتوری واقعی اشاره می‌کند → ریدایرکت کن
if (!isset($_GET['dir'])) {
    $reqPath = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)); // مثل /N/anime
    $fsPath  = ltrim($reqPath, '/');                                        // N/anime
    if ($fsPath !== '' && is_dir($fsPath)) {
        header('Location: /?dir=' . encode_path($fsPath), true, 302);
        exit;
    }
}

$lister = new DirectoryLister();

// Restrict access to current directory
ini_set('open_basedir', getcwd());

// Return file hash
if (isset($_GET['hash'])) {

    // Get file hash array and JSON encode it
    $hashes = $lister->getFileHash($_GET['hash']);
    $data   = json_encode($hashes);

    // Return the data
    die($data);
}

if (isset($_GET['zip'])) {

    $dirArray = $lister->zipDirectory($_GET['zip']);
} else {

    // Initialize the directory array
    if (isset($_GET['dir'])) {
        $dirArray = $lister->listDirectory($_GET['dir']);
    } else {
        $dirArray = $lister->listDirectory('.');
    }

    // Define theme path
    if (!defined('THEMEPATH')) {
        define('THEMEPATH', $lister->getThemePath());
    }

    // Set path to theme index
    $themeIndex = $lister->getThemePath(true) . '/index.php';

    // Initialize the theme
    if (file_exists($themeIndex)) {
        include($themeIndex);
    } else {
        die('ERROR: Failed to initialize theme');
    }
}
