<?php
defined(page_security_key) or exit;

if (debug && debug_id == $_SESSION['id']){
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);  
}
include_once './assets/functions.php';
include_once './settings/settings_redirector.php';

$page = 'media';
//Check if allowed
if (isAllowed($page,$_SESSION['profile'],$_SESSION['permission'],'R') === 0){
    header('location: index.php');
    exit;
}
//PAGE Security
$update_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'U');
$delete_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'D');
$create_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'C');


//GET PARAMETERS
$pagination_page = isset($_GET['p']) ? $_GET['p'] : 1;
$search = isset($_GET['search']) ? '&search='.$_GET['search'] : '';

//SET PAGE ORIGIN FOR NAVIGATION AND SECURITY
$prev_page = $_SESSION['prev_origin'] ?? '';
$page = $_SESSION['origin'] = 'media';

// Determine the URL
$url = 'index.php?page='.$page.$search;
//GET Details from URL
$GET_VALUES = urlGETdetails($_GET) ?? '';
//CALL TO API
$api_url = '/v2/media/'.$GET_VALUES;
$responses = ioServer($api_url,'');

//Decode Payload
if (!empty($responses)){$responses = json_decode($responses,true);}else{$responses = null;}

//Return QueryTotal from API
$api_url = '/v2/media/'.$GET_VALUES.'&totals=';
$query_total = ioServer($api_url,'');
//Decode Payload
if (!empty($query_total)){$query_total = json_decode($query_total,true);}else{$query_total = null;}
// Handle success messages
if (isset($_GET['success_msg'])) {
    if ($_GET['success_msg'] == 1) {
        $success_msg = $message_media_1 ?? 'Created';
    }
    if ($_GET['success_msg'] == 2) {
        $success_msg = $message_media_2 ?? 'Updated';
    }
    if ($_GET['success_msg'] == 3) {
        $success_msg = $message_media_3 ?? 'Deleted';
    }
}

if (isset($_FILES['fileToUpload']) && $create_allowed === 1) {
    //UPLOAD ALL PICTURES
    $target_dir = dirname(__FILE__)."/assets/images/media/";

    foreach ($_FILES["fileToUpload"]['name'] as $key => $value){

        //ONLY UPDATE PICTURES IF SOMETHING IS RETURNED
        if($value !='' || !empty($value)){
            $title = $_FILES["fileToUpload"]['name'][$key];
            $full_path = $target_dir . $title;
            
            move_uploaded_file($_FILES["fileToUpload"]["tmp_name"][$key], $full_path);
            
            //GET ALL POST DATA
            $payload = [
                'title' => $title,
                'full_path' => "/assets/images/media/$title"
            ];
            
            $payload = json_encode($payload, JSON_UNESCAPED_UNICODE);
            //API call
            $responses = ioServer('/v2/media', $payload);
        }
    }   
    header('Location: index.php?page=media&success_msg=1');
    exit;
}

template_header('Media', 'media' ,'view');
$view = '
<div class="content-title">
    <div class="title">
        <i class="fa-solid fa-photo-film"></i>
        <div class="txt">
            <h2>'.($media_h2 ?? 'Media').' ('.$query_total.')</h2>
            <p>'.($media_p ?? 'View, manage, and search media details.').'</p>
        </div>
    </div>
</div>';

if (isset($success_msg)){
$view .= ' <div class="msg success">
                <i class="fas fa-check-circle"></i>
                <p>'.$success_msg.'</p>
                <i class="fas fa-times"></i>
            </div>';
}
$view .= '
<div class="content-header responsive-flex-column pad-top-5">';
if ($create_allowed ===1 && isAllowed('media_scanner' ,$_SESSION['profile'],$_SESSION['permission'],'C') === 1){
    $view .= '<a href="index.php?page=media_scanner" class="btn">'.($button_media_scanner ?? 'media_scanner').'</a>';
}

if ($create_allowed ===1){
    $view .= '    
    <form action="" method="post" enctype="multipart/form-data">
        <input type="file" onchange="this.form.submit()" name="fileToUpload[]" id="fileToUpload" accept=".png, .PNG, .jpg,.JPG,.jpeg,.JPEG" style="width: 30%;padding: 50px 0 0 0;height: 10px;" multiple>         
    </form>';    
}

$view .= '    
    <form action="" method="get">
        <input type="hidden" name="page" value="media">
            <div class="filters">
                <a href="#"><i class="fa-solid fa-filter"></i>'.$general_filters.'</a>
                <div class="list">
                <select name="status">
                    <option value="" disabled selected>Active</option>
                    <option value="0">'.$disabled.'</option>
                    <option value="1">'.$enabled.'</option>    
                </select>
                <button type="submit">'.$button_apply.'</button>
            </div>
        </div>';     
$view .= '<div class="search">
            <label for="search">
                <input id="search" type="text" name="search" placeholder="'.($media_search  ?? 'Search media...').'" value="" class="responsive-width-100">
                <i class="fas fa-search"></i>
            </label>
        </div>
    </form>
</div>
';

$view .= '
<div class="content-block">
    <div style="display: grid; grid-template-columns: repeat(5, 1fr); gap: 10px; margin: 20px 0;">';
    
    foreach ($responses as $response){   
        $view .= '<a href="index.php?page=media_manage&rowID='.$response['rowID'].'">
                    <img src="'.$response['full_path'].'" title="'.$response['title'].'" alt="'.$response['title'].'" style="width: 100%; cursor: pointer; border: 2px solid transparent;" onmouseover="this.style.border=\'2px solid #4CAF50\'" onmouseout="this.style.border=\'2px solid transparent\'">
                </a>';
        }        
$view .= '</div>
</div>
';

$view.='<div class="pagination">';
if ($pagination_page > 1) {
    $page = $pagination_page-1;
    $view .= '<a href="'.$url.'&p=1">'.$general_first.'</a>';
    $view .= '<a href="'.$url.'&p='.$page.'">'.$general_prev.'</a>';
}
$totals = ceil($query_total / $page_rows_media) == 0 ? 1 : ceil($query_total / $page_rows_media);
$view .= '<span> '.$general_page.$pagination_page.$general_page_of.$totals.'</span>';
if ($pagination_page * $page_rows_media < $query_total){
    $page = $pagination_page+1;
    $view .= '<a href="'.$url.'&p='.$page.'">'.$general_next.'</a>';
    $view .= '<a href="'.$url.'&p='.$totals.'">'.$general_last.'</a>';
}
$view .= '</div>';
//OUTPUT
echo $view;

template_footer();
?>