<?php
class FOAdmin extends Base {

    
    public static function index($page) {

        if (empty($_COOKIE['admin_verify']) OR $_COOKIE['admin_verify'] != md5(PASSWORD)) {
            header("Location: /");
            exit;
        }
        
        $p = Flight::page();
                
        $pages = $p->menu('fo_video', '/porno-obmenik-video/admin', $page, "WHERE `moderation` = '0'", FO_PERPAGE);
                
        $files = Flight::db()
        ->query("SELECT *, (SELECT COUNT(*) FROM fo_comments WHERE fo_comments.parent = fo_video.id) AS count_comments FROM `fo_video` ORDER BY `fo_video`.`moderation` DESC, `fo_video`.`id` DESC " . $p->limit())
        ->fetchAll();

        if (!empty($_SESSION['message'])) {
            $message = $_SESSION['message'];
        }
        unset($_SESSION['message']);
                                
        parent::view('fo_admin/files', [
        'title'       => 'Обменник файлов',
        'description' => '',
        'keywords'    => '',
        'files' => $files,
        'pagination' => $pages,
        'message' => (!empty($message) ? $message : '')
        ]); 
        
    }
    
    public static function settings() {
        
        if (empty($_COOKIE['admin_verify']) OR $_COOKIE['admin_verify'] != md5(PASSWORD)) {
            header("Location: /");
            exit;
        }
        
        $settings = Flight::db()
        ->query("SELECT * FROM `fo_settings`")
        ->fetch();
        
        if (!empty($_POST['save'])) {
            $cron_del = (empty($_POST['cron_del']) ? '' : $_POST['cron_del']);            
            $sql = "UPDATE fo_settings SET cron_del = :cron_del_val";
            $result = Flight::db()->prepare($sql);
            $result->bindValue(":cron_del_val", $cron_del, PDO::PARAM_STR);
            $result->execute(); 
            
            $message = 'Настройки успешно сохранены';
        }
        
        parent::view('fo_admin/settings', [
        'title'       => 'Настройки обменника',
        'description' => '',
        'keywords'    => '',
        'settings' => $settings,
        'message' => (!empty($message) ? $message : '')
        ]); 
    }
    
    public static function dey($dey) {

        if (empty($_COOKIE['admin_verify']) OR $_COOKIE['admin_verify'] != md5(PASSWORD)) {
            header("Location: /");
            exit;
        }
                
        $root = $_SERVER['DOCUMENT_ROOT'];

        if (!isset($_GET['yes'])) {
            parent::view('fo_admin/verification', [
            'title'       => 'Подтверждение действия',
            'description' => '',
            'keywords'    => '',
            'dey' => $dey
            ]); 
        } else {        
            switch ($dey) {
                
                case 'moder_all':
                    Flight::db()->query("UPDATE fo_video SET moderation = '0'"); 
                    $_SESSION['message'] = 'Все видео промодерированы'; 
                    header("Location: /porno-obmenik-video/admin");
                    exit;          
                    break;
                    
                case 'del_moder_all':
                    $files = Flight::db()
                    ->query("SELECT * FROM `fo_video` WHERE moderation = '1'")
                    ->fetchAll();            
                    
                    foreach ($files as $file) {
                        $video = $root . '/public/video_fo/' . PREFIX . $file['alias'] . '.' . $file['ext'];;
                        $screen = $root . '/public/screen_fo/' . $file['alias'] . '.png';
                        
                        @unlink($video);
                        @unlink($screen);
                        
                        Flight::db()->query("DELETE FROM `fo_comments` WHERE parent = '{$file['id']}'");
                        Flight::db()->query("DELETE FROM `fo_rating_list` WHERE video_id = '{$file['id']}'");
                    }
                    
                    Flight::db()->query("DELETE FROM `fo_video` WHERE moderation = '1'");
                    
                    $_SESSION['message'] = 'Все видео на модерации - удалены'; 
                    header("Location: /porno-obmenik-video/admin");
                    exit; 
                    break;
                    
                case 'clear_fo':
                    $files = Flight::db()
                    ->query("SELECT * FROM `fo_video`")
                    ->fetchAll();            
                    
                    foreach ($files as $file) {
                        $video = $root . '/public/video_fo/' . PREFIX . $file['alias'] . '.' . $file['ext'];;
                        $screen = $root . '/public/screen_fo/' . $file['alias'] . '.png';
                        
                        @unlink($video);
                        @unlink($screen);
                        
                        Flight::db()->query("DELETE FROM `fo_comments` WHERE parent = '{$file['id']}'");
                        Flight::db()->query("DELETE FROM `fo_rating_list` WHERE video_id = '{$file['id']}'");
                    }
                    
                    Flight::db()->query("DELETE FROM `fo_video`");
                    
                    $_SESSION['message'] = 'Все видео - удалены'; 
                    header("Location: /porno-obmenik-video/admin");
                    exit;             
                    break;
                    
                case 'clear_comm_fo':
                    Flight::db()->query("DELETE FROM `fo_comments`");
                    $_SESSION['message'] = 'Все комментарии - удалены'; 
                    header("Location: /porno-obmenik-video/admin");
                    exit;
                    break;
                    
                case 'del_files_max180':         
                    $files = Flight::db()
                    ->query("SELECT * FROM `fo_video` WHERE `date_upload` < UNIX_TIMESTAMP(NOW() - INTERVAL 180 DAY) && cron_del = '1'")
                    ->fetchAll();            
                    
                    foreach ($files as $file) {
                        $video = $root . '/public/video_fo/' . PREFIX . $file['alias'] . '.' . $file['ext'];;
                        $screen = $root . '/public/screen_fo/' . $file['alias'] . '.png';
                        
                        @unlink($video);
                        @unlink($screen);
                        
                        Flight::db()->query("DELETE FROM `fo_comments` WHERE parent = '{$file['id']}'");
                        Flight::db()->query("DELETE FROM `fo_rating_list` WHERE video_id = '{$file['id']}'");
                    }
                    
                    Flight::db()->query("DELETE FROM `fo_video` WHERE `date_upload` < UNIX_TIMESTAMP(NOW() - INTERVAL 180 DAY) && cron_del = '1'");
                    
                    $_SESSION['message'] = 'Все видео загруженные более 180 суток назад - удалены'; 
                    header("Location: /porno-obmenik-video/admin");
                    exit;         
                    break;
                    
                case 'del_files_min180':
                    $files = Flight::db()
                    ->query("SELECT * FROM `fo_video` WHERE date_upload > UNIX_TIMESTAMP(NOW() - INTERVAL 180 DAY) && cron_del = '1'")
                    ->fetchAll();            
                    
                    foreach ($files as $file) {
                        $video = $root . '/public/video_fo/' . PREFIX . $file['alias'] . '.' . $file['ext'];;
                        $screen = $root . '/public/screen_fo/' . $file['alias'] . '.png';
                        
                        @unlink($video);
                        @unlink($screen);
                        
                        Flight::db()->query("DELETE FROM `fo_comments` WHERE parent = '{$file['id']}'");
                        Flight::db()->query("DELETE FROM `fo_rating_list` WHERE video_id = '{$file['id']}'");
                    }
                    
                    Flight::db()->query("DELETE FROM `fo_video` WHERE date_upload > UNIX_TIMESTAMP(NOW() - INTERVAL 180 DAY) && cron_del = '1'");
                    
                    $_SESSION['message'] = 'Все видео загруженные более 180 суток назад - удалены'; 
                    header("Location: /porno-obmenik-video/admin");
                    exit;             
                    break;
                
            }
        }
        
    }
    
    public static function file_adm($type, $id) {

        if (empty($_COOKIE['admin_verify']) OR $_COOKIE['admin_verify'] != md5(PASSWORD)) {
            header("Location: /");
            exit;
        }
        
        $result = Flight::db()->prepare("SELECT * FROM `fo_video` WHERE id = :id");
        $result->bindValue(":id", $id, PDO::PARAM_STR);
        $result->execute(); 
        $file = $result->fetch(PDO::FETCH_ASSOC);
        
        
        switch ($type) {
            
            case 'edit':

                if (!empty($_POST)) {
                    
                    $err = array();
                    $name = trim(htmlspecialchars($_POST['name']));
                    $name_f = trim(htmlspecialchars($_POST['name_f']));
                    $desc_f = trim(htmlspecialchars($_POST['desc_f']));
                    $comments = (empty($_POST['comments']) ? '' : trim(htmlspecialchars($_POST['comments'])));
                    
                    if (empty($name)) {
                        $err[] = 'Заполните поле "Ваше имя"';
                    }
                    
                    if (empty($name_f)) {
                        $err[] = 'Заполните поле "Название видео"';
                    }
                    
                    if (empty($desc_f)) {
                        $err[] = 'Заполните поле "Описание видео"';
                    }
                    
                    if (strlen($desc_f) > 600) {
                        $err[] = 'Длина описания превышает 600 символов';
                    }
                    
                    if (empty($err)) {
                        
                        $sql = "
                        UPDATE fo_video SET
                        file_name = :name_f, file_desc = :desc_f, file_comments = :comments, user_name = :name
                        WHERE id = '".$file['id']."'
                        ";
                                     
                        $result = Flight::db()->prepare($sql);
                        $result->bindValue(":name_f", $name_f, PDO::PARAM_STR);
                        $result->bindValue(":desc_f", $desc_f, PDO::PARAM_STR);
                        $result->bindValue(":comments", $comments, PDO::PARAM_INT);
                        $result->bindValue(":name", $name, PDO::PARAM_STR);
                        $result->execute(); 
                        
                        $_SESSION['message'] = 'Файл успешно обновлен';
                        
                        header("Location: /porno-obmenik-video/admin");
                        exit;
                    }
                }
                parent::view('fo_admin/file_edit', [
                'title'       => 'Редактирование файла',
                'description' => '',
                'keywords'    => '',
                'file' => $file
                ]);                 
                break;
                
            case 'add':
                $sql = "UPDATE fo_video SET moderation = '0' WHERE id = '".$file['id']."'";
                $result = Flight::db()->prepare($sql);
                $result->execute(); 
                $_SESSION['message'] = 'Файл допущен';
                header("Location: /porno-obmenik-video/admin"); 
                exit;               
                break;
                
            case 'del':
                if (isset($_GET['yes'])) {
                    $sql = "DELETE FROM fo_video WHERE id = '".$file['id']."'";
                    $result = Flight::db()->prepare($sql);
                    $result->execute(); 
                    
                    $sql = "DELETE FROM fo_comments WHERE parent = '".$file['id']."'";
                    $result = Flight::db()->prepare($sql);
                    $result->execute(); 
                    
                    $sql = "DELETE FROM fo_rating_list WHERE video_id = '".$file['id']."'";
                    $result = Flight::db()->prepare($sql);
                    $result->execute(); 
                    
                    $root = $_SERVER['DOCUMENT_ROOT'];
                    $alias_path = PREFIX . $file['alias'];
                    @unlink($root . '/public/video_fo/' . $alias_path . '.' . $file['ext']);
                    @unlink($root . '/public/screen_fo/' . $file['alias'] . '.png');
                                        
                    $_SESSION['message'] = 'Файл удален';
                    header("Location: /porno-obmenik-video/admin"); 
                    exit;                     
                }
                parent::view('fo_admin/file_delete', [
                'title'       => 'Удаление файла',
                'description' => '',
                'keywords'    => '',
                'file' => $file
                ]);              
                break;
                
        }
        
    }
    
}