<?php
require_once '../header.php';
$dirs = array();
$dir_name = array();
$files = array();
$rename_file_name = array();
$filesSelectedNow = false;
$directory = Input('dir_path') ? Input('dir_path') : 'upload_file/fm';
$dir_path = $directory;
$cid = Input('cid');

$parentCat = $db->where('id', $cid)->getOne(TABLE_CAT, 'name');
if (InputArray('checkedFiles')) {
    foreach (InputArray('checkedFiles') as $key => $value) {
        $files[] = $value;
        $rename_file_name[] = Input('rename_' . md5($value));
    }
    $filesSelectedNow = true;
    //print_r($files); exit;
} elseif ($directory) {
    $dir = $RootPath . '/' . $directory;
    $replaceText = explode(',', Input('replaceText'));
    if ($dh = @opendir($dir)) {
        while (false !== ($file = readdir($dh))) {
            if ($file == '.' || $file == '..' || substr($file, 0, 9) == '.htaccess')
                continue;
            $path = $dir . '/' . $file;
            if (is_dir($path)) {
                $dirs[] =  base64_encode(str_replace($RootPath, @APP_URL, str_replace(' ', '%20', $path)));
                $dir_name[] = base64_encode($file);
            } else
            if (is_file($path)) {
                $files[str_replace($replaceText, '', $file)] = base64_encode(str_replace($RootPath . '/', '', str_replace(' ', '%20', $path)));
                $rename_file_name[str_replace($replaceText, '', $file)] = base64_encode(str_replace($replaceText, '', $file));
            }
        }
        closedir($dh);
    }
}
asort($dirs);
if (Input('commit') == 'Show Z-A') {
    krsort($files);
    krsort($rename_file_name);
} else {
    ksort($files);
    ksort($rename_file_name);
}
$dirs = $dirs;
$dir_name = $dir_name;
$files = $files;
$rename_file_name = $rename_file_name;
$replaceText = Input('replaceText');
$thumbUrl = Input('thumb_url') ? base64_encode(Input('thumb_url')) : '';
$thumbnail = Input('thumb_url') ? 'YES' : 'NO';
$filestatus = Input('file_status') ? Input('file_status') : 0;
$filetrend = Input('file_trend') ? Input('file_trend') : 0;
$filenew = Input('file_new') ? Input('file_new') : 0;
$delayAction = 1000;

$pathc = '';
if ($parentid = Input('cid')) {
    $pathc = '<li class="breadcrumb-item"><a href="../category/index.php">Home</a></li>';
    $db->where('id', $parentid);
    $category = $db->getOne(TABLE_CAT);
    $title = $category['name'];

    $parentids = array_filter(explode('/', $category['folder']));
    array_shift($parentids);

    if ($parentids) {
        $breadcrumbs = $db->where('id', $parentids, 'IN')->orderBy('id', 'ASC', $parentids)->get(TABLE_CAT);
        foreach ($breadcrumbs as $bread) {
            if ($bread['totalitem'] > 0 && $bread['subcate'] == 0)
                $pathc .= '<li class="breadcrumb-item"><a href="../files/index.php?cid=' . $bread['id'] . '">' . $bread['name'] . '</a></li>';
            else {
                $pathc .= '<li class="breadcrumb-item"><a href="../category/index.php?parentid=' . $bread['id'] . '">' . $bread['name'] . '</a></li>';
            }
        }
    }
}
?>
<div class="container-fluid">
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <?php echo $pathc; ?>
        </ol>
    </nav>
    <div class="card shadow mb-4">
        <div class="card-header py-3">

            <div class="d-flex justify-content-between">
                <h6 class="m-0 font-weight-bold text-primary">Multiple Uploader to <?php echo $category['name']; ?>:</h6>
            </div>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-lg-4">
                    <div class="alert alert-info">
                        You can upload files Via FTP OR SFTP. Upload <strong><?php echo $RootPath; ?>/upload_file/fm </strong> Directory
                    </div>
                    <form name="UploadNew" enctype="multipart/form-data" method="post" action="multiAction.php">
                        <input type="hidden" name="cid" id="cid" value="<?php echo $cid; ?>" />
                        <input type="hidden" name="dir_path" value="<?php echo $directory; ?>" />
                        <div class="form-group">
                            <label for="URL">URL <small>(Allow: Zip, Mp3)</small></label>
                            <input type="text" name="copy_url[]" class="form-control" id="copy_url" value="" placeholder="Copy File Via URL" />
                            <div id="input_url_more"></div>
                        </div>

                        <div class="form-group">
                            <label for="File">File <small>(Allow: Zip, Mp3)</small></label>
                            <input type="file" name="uploadfile[]" class="form-control" id="uploadfile" value="" />
                            <div id="input_file_more"></div>
                            <button type="button" id="addmoreurl" class="btn btn-default">Add More URL</button>
                            <button type="button" id="addmorefile" class="btn btn-default">Add More File</button>
                            <input type="submit" class="btn btn-success m-1" name="upload" value="Submit" />
                        </div>
                    </form>

                    <form name="Files" enctype="multipart/form-data" method="post" action="multi.php?cid=<?php echo $cid; ?>">
                        <input type="hidden" name="cid" id="cid" value="<?php echo $cid; ?>" />
                        <input type="hidden" name="dir_path" value="<?php echo $directory; ?>" />
                        <div class="form-group">
                            <label for="replaceText">Replace Text:</label>
                            <input type="text" name="replaceText" class="form-control" id="replaceText" value="<?php echo $replaceText; ?>" placeholder="Multiple Using Comma Ex: name,name2,name3" />
                            <input type="submit" class="btn btn-success mt-1" name="commit" value="Show A-Z" />
                            <input type="submit" class="btn btn-danger mt-1" name="commit" value="Show Z-A" />
                            <a class="btn btn-dark mt-1" href="multi.php?cid=<?php echo $cid; ?>">Home</a>

                        </div>
                    </form>
                </div>

                <div class="col-lg-8">
                    <?php
                    if ($filesSelectedNow == true) {
                        $flist = $fileNewName = '';
                        echo '<div class="table-responsive">
    <table class="table table-striped table-bordered table-hover">
    <thead>
    <tr>
    <th>Upload</th>
    <th>Name</th>
       <th>Thumnail</th>
    </tr>
    </thead>
    <tbody>';
                        foreach ($files as $key => $value) {
                            //echo $value;
                            $flist .= "'" . $value . "', ";
                            $fileNewName .= "'" . $rename_file_name[$key] . "', ";
                            echo '<tr id="' . $value . '">';
                            echo '<td id="get_' . $value . '"><a href="" onclick="UploadFiles(\'' . $value . '\',' . $cid . ',\'' . $rename_file_name[$key] . '\', \'' . $thumbUrl . '\', \'' . $filestatus . '\', \'' . $filenew . '\', \'' . $filetrend . '\'); return false;">Upload</a></td>';
                            echo '<td>' . $rename_file_name[$key] . '</td>';
                            echo '<td>' . $thumbnail . '</td>';
                            echo '</tr>';
                        }
                        echo '</tbody></table>
	</div>';
                        $flist = substr($flist, 0, -2);
                        $fileNewName = substr($fileNewName, 0, -2);
                    ?>
                        <script type="text/javascript">
                            // write id to whom we have to invide
                            var webpath = 'createAction.php';
                            var flist = new Array(<?php echo $flist; ?>);
                            var fileNewName = new Array(<?php echo $fileNewName; ?>);
                            var cid = <?php echo $cid; ?>;
                            var thumbUrl = <?php echo "'" . $thumbUrl . "'"; ?>;
                            var status = <?php echo "'" . $filestatus . "'"; ?>;
                            var trend = <?php echo "'" . $filetrend . "'"; ?>;
                            var newtag = <?php echo "'" . $filenew . "'"; ?>;

                            var c = 1;
                            var t;

                            function UploadFiles(id, cid, newName, thumbUrl, status, newtag, trend) {
                                //alert(category);
                                var xmlhttp; // The variable that makes Ajax possible!
                                try {
                                    // Opera 8.0+, Firefox, Safari
                                    xmlhttp = new XMLHttpRequest();
                                } catch (e) {
                                    // Internet Explorer Browsers
                                    try {
                                        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                                    } catch (e) {
                                        try {
                                            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                                        } catch (e) {
                                            // Something went wrong
                                            alert("Your browser broke!");
                                            return false;
                                        }
                                    }
                                }

                                // Create a function that will receive data sent from the server
                                xmlhttp.onreadystatechange = function() {
                                    if (xmlhttp.readyState == 4) {
                                        var resp = JSON.parse(xmlhttp.responseText);
                                        console.log(resp.message);
                                        document.getElementById(resp.message).style.background = '#eceff4';
                                        document.getElementById('get_' + resp.message).innerHTML = '<span class="text-success">Success</span>';
                                    }
                                }
                                var data = 'filefrom=MULTI';
                                data += '&thumbfrom=EXTERNAL_LINK';
                                data += '&url=' + id;
                                data += '&cid=' + cid;
                                data += '&filename=' + newName;
                                data += '&thumb_url=' + thumbUrl;
                                data +='&status='+status;
                                data +='&new_tag='+newtag;
                                data +='&trend='+trend;
                                xmlhttp.open("POST", "" + webpath, true);
                                xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                                xmlhttp.send(data);
                            }

                            function timedCount() {
                                // get 1 value from array
                                add = flist.shift();
                                addNewName = fileNewName.shift();
                                // open url to add friend
                                UploadFiles(add, cid, addNewName, thumbUrl,status,newtag,trend);

                                // write current working log
                                document.getElementById('Total').innerHTML = 'Total Files Requested: ' + c;

                                // add link to div id="added"
                                document.getElementById(add).style.background = '#fff85b';

                                // total counter
                                c = c + 1;

                                // stop function if array is empty
                                if (flist == '') {
                                    document.getElementById('Total').innerHTML = document.getElementById('Total').innerHTML + ' <strong>Please Wait Before Success</strong>';
                                    stopCount();
                                    exit(1);
                                }
                                t = setTimeout("timedCount()", document.getElementById('delay').value);
                            }

                            function stopCount() {
                                clearTimeout(t);
                            }
                        </script>
                        <div class="form-inline">
                            <div class="form-group">
                                <label for="delay">Delay </label>
                                <input type="text" class="form-control" id="delay" value="<?php echo $delayAction; ?>" />
                            </div>
                            <button type="button" onClick="timedCount();" class="btn btn-info ml-1 mr-1">Start Upload</button>
                            <button type="button" onClick="stopCount();" class="btn btn-warning">Stop Upload</button>
                        </div>

                        <div class="alert alert-success mt-2" role="alert">
                            <div id="Total">Files not upload yet:</div>
                        </div>
                    <?php
                    } elseif ($files || $dirs) {


                        echo '<form id="new" method="post" action="#">';
                        echo '<div class="table-responsive">
                        <table class="table table-striped table-bordered table-hover">
                        <thead>
                        <tr>
                        <th>Name (Explore Folder)</th>
                        <th>Action</th>
                        </tr>
                        </thead>
                        <tbody>';
                        if ($dirs) :
                            foreach ($dirs as $key => $value) {
                                echo '<tr>';
                                echo '<td><input type="submit" class="btn btn-default" value="' . $dir_path . '/' . base64_decode($dir_name[$key]) . '" name="dir_path"/></td>';
                                echo '<td><a class="btn btn-danger" href="multiAction.php?cid=' . $cid . '&deletefile=' . base64_encode($dir_path . '/' . base64_decode($dir_name[$key])) . '">Delete</a></td>';
                                echo '</tr>';
                            }
                        endif;
                        foreach ($files as $key => $value) {
                            $NewFileType = strtolower(pathinfo(base64_decode($rename_file_name[$key]), PATHINFO_EXTENSION));
                            if ($NewFileType == 'zip') {
                                echo '<tr>';
                                echo '<td>' . base64_decode($rename_file_name[$key]) . '</td>';
                                echo '<td><a class="btn btn-default" href="multiAction.php?cid=' . $cid . '&decompress=' . $rename_file_name[$key] . '&dir_path=' . $dir_path . '">Unzip</a>  <a class="btn btn-danger" href="multiAction.php?cid=' . $cid . '&deletefile=' . base64_encode($dir_path . '/' . base64_decode($rename_file_name[$key])) . '">Delete</a></td>';
                                echo '</tr>';
                            }
                        }
                        echo '</tbody></table></div>';
                        echo '</form>';

                        echo '<form id="gForm" method="post" action="#" class="form-horizontal">
<input type="hidden" name="dir_path" id="dir_path" value="' . $dir_path . '" />
<input type="hidden" name="cid" id="cid" value="' . $cid . '" />
<input type="hidden" name="replaceText" id="replaceText" value="' . $replaceText . '" />';
                        echo '<div class="table-responsive">
    <table class="table table-striped table-bordered table-hover">
    <thead>
    <tr>
    <th>Select</th>
    <th>Rename</th>
     <th>Action</th>
    </tr>
    </thead>
    <tbody>';
                        foreach ($files as $key => $value) {
                            $NewFileType = strtolower(pathinfo(base64_decode($rename_file_name[$key]), PATHINFO_EXTENSION));
                            if ($NewFileType == 'mp3') {
                                echo '<tr>';
                                echo '<td><input type="checkbox" name="checkedFiles[]" id="checkedFiles_' . $value . '" value="' . $value . '" /></td>';
                                echo '<td><input type="text" class="form-control" name="rename_' . md5($value) . '" id="' . $value . '" value="' . base64_decode($rename_file_name[$key]) . '"/></td>';
                                echo '<td><a class="btn btn-danger btn-sm" href="multiAction.php?cid=' . $cid . '&deletefile=' . base64_encode($dir_path . '/' . base64_decode($rename_file_name[$key])) . '">Delete</a></td>';
                                echo '</tr>';
                            }
                        }
                        echo '</tbody></table></div>';
                    ?>
                        <button type="button" onclick="checkedAll('gForm')" class="btn btn-secondary">Select All</button>

                        <div class="form-group form-row mt-2">
                            <label class="col-sm-2 control-label">All Thumbnail:</label>
                            <div class="col-sm-10">
                                <input type="text" name="thumb_url" class="form-control" id="thumb_url" value="" placeholder="Please Enter Vaild Thumbnail Url" />
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group col-md-3 align-self-end">
                                <label for="appname">Added Home</small></label>
                                <input type="checkbox" class="form-control" data-toggle="switch" name="file_new" value="1" checked />
                            </div>
                            <div class="form-group col-md-3 align-self-end">
                                <label for="trend">Trend:</label>
                                <input type="checkbox" class="form-control" data-toggle="switch" name="file_trend" value="1" />
                            </div>
                            <div class="form-group col-md-3 align-self-end">
                                <label for="status">Status:</label>
                                <input type="checkbox" class="form-control" data-toggle="switch" name="file_status" value="1" checked />
                            </div>
                        </div>
                        <div class="col-sm-4">
                            <input type="submit" class="btn btn-primary" name="commit" value="Upload Selected" />
                        </div>
                        </form>
                        <script type="text/javascript">
                            checked = false;

                            function checkedAll(frm1) {
                                var aa = document.getElementById(frm1);
                                if (checked == false) {
                                    checked = true;
                                } else {
                                    checked = false;
                                }
                                for (var i = 0; i < aa.elements.length; i++) {
                                    if (aa.elements[i].name == "checkedFiles[]")
                                        aa.elements[i].checked = checked;
                                }
                            }
                        </script>
                    <?php
                    }
                    ?>
                </div>

            </div>

        </div>

    </div>
</div>

<?php
require_once '../footer.php';
