<?php

/**
 * The functionality of the module.
 *
 * @package    TS Forms extended
 * @author     Max Sternitzke <max.sternitzke@th-luebeck.de>
 */
class Trainingssystem_Plugin_Module_Forms_Media_Grid {

    /**
     * FRONTEND 
     * 
     * Shows the media grid with various options
     * 
     * @param Array Shortcode Attributes
     * 
     * @return HTML-Code
     */
    public function showMediaGrid($atts) {
        $view = null;
        if(isset($atts['view']) && trim($atts['view']) != "" && trim($atts['view']) == "all") {
            $view = "all";
        } else if(isset($atts['view']) && trim($atts['view']) != "" && trim($atts['view']) == "boss") {
            $view = "boss";
        }else if(isset($atts['view']) && trim($atts['view']) != "" && trim($atts['view']) == "kAdmin"){
            $view = "kAdmin";
        }else if(isset($atts['view']) && trim($atts['view']) != "" && trim($atts['view']) == "my") {
            $view = "my";
        }

        $uploadfieldid = null;
        if(isset($atts['uploadfieldid']) && trim($atts['uploadfieldid']) != "") {
            $uploadfieldid = $atts['uploadfieldid'];
        }

        $projectfieldid = null;
        if(isset($atts['projectfieldid']) && trim($atts['projectfieldid']) != "") {
            $projectfieldid = $atts['projectfieldid'];
        }

        $titlefieldid = null;
        if(isset($atts['titlefieldid']) && trim($atts['titlefieldid']) != "") {
            $titlefieldid = $atts['titlefieldid'];
        }

        $descfieldid = null;
        if(isset($atts['descfieldid']) && trim($atts['descfieldid']) != "") {
            $descfieldid = $atts['descfieldid'];
        }

        $defaultimage = "data:image/png;base64, ";
        $imagefail = false;
        if(isset($atts['defaultimage']) && trim($atts['defaultimage']) != "") {
            if(is_file($atts['defaultimage'])) {
                $defaultimage = $atts['defaultimage'];
            } else {
                $imagefail = true;
            }
        }

        $latest = null;
        if(isset($atts['latest']) && trim($atts['latest']) != "" && is_numeric($atts['latest'])) {
            $latest = $atts['latest'];
        }
        
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        if($view != null && $uploadfieldid != null && !$imagefail) {

            $usermodus = false;
            $uid = get_current_user_id();
            $selectui = '' . get_user_meta(wp_get_current_user()->ID, 'coach_select_user', true);
            if ($selectui != '') {
                $uid = $selectui;
                $usermodus = true;
            }

            $includeFields = array();
            $includeFields[] = $uploadfieldid;
            if ($projectfieldid != null) { $includeFields[] = $projectfieldid; }
            if ($titlefieldid != null) { $includeFields[] = $titlefieldid; }
            if ($descfieldid != null) { $includeFields[] = $descfieldid; }

            $userids = null;
            if($view == "boss") {
                $uids = Trainingssystem_Plugin_Database::getInstance()->CompanygroupUserDao->getUserIdsByBossId($uid);
                if($uids == null) {
                    return $twig->render("forms-media-grid/media-grid-noboss.html");
                }
                $userids = $uids;
            } else if($view == "kAdmin"){
                $kAdminUsers = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getAllUserIdsByCreaterId($uid);
                
                if($kAdminUsers == null){
                    return $twig->render("forms-media-grid/media-grid-nokadmin.html");
                }
                $userids = $kAdminUsers;
            } else if($view == "all") {
                $userids = null;
            } else if($view == "my") {
                $userids = $uid;
            }

            $rawdata = Trainingssystem_Plugin_Database::getInstance()->Formdata->getMediaGridData($userids, $includeFields, $latest);
            
            $i = 0;
            $data = array();
            $data[$i] = array();

            if($projectfieldid == null) {
                $data[$i]['title'] = "";
                $data[$i]['id'] = bin2hex(random_bytes(32));
                $data[$i]['userid'] = "";
                $data[$i]['data'] = $rawdata;
            } else {
                foreach($rawdata as $savedate => $savepoint) {
                    foreach($savepoint as $fieldid => $value) {
                        if($fieldid == $projectfieldid) {
                            $found = false;
                            foreach($data as $index => $d) {
                                if(isset($d['title']) && trim($d['title']) == $value->getData() &&
                                    isset($d['userid']) && $d['userid'] == $value->getUserId()) {
                                    $data[$index]['data'][$savedate] = $savepoint;
                                    $found = true;
                                }
                            }
                            if(!$found) {
                                $data[$i]['title'] = $value->getData();
                                $data[$i]['id'] = bin2hex(random_bytes(32));
                                $data[$i]['userid'] = $value->getUserId();
                                $data[$i]['data'] = array();
                                $data[$i]['data'][$savedate] = $savepoint;
                                $i++;
                            }
                        }
                    }
                }
            }

            $usernames = array();
            if($view != "my") {
                $blogusers = get_users(['orderby' => 'display_name', 'order' => 'ASC']);
                foreach($blogusers as $user) {
                    $usernames[$user->ID] = $user->display_name;
                }
            } else {
                $user_info = get_userdata($uid);
                $usernames[$uid] = $user_info->display_name;
            }

            $weekdays = ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"];
            
            return $twig->render("forms-media-grid/media-grid.html", ["rand" => bin2hex(random_bytes(16)),
                                                                        "latest" => $latest,
                                                                        "defaultimage"=> $defaultimage,
                                                                        "data" => $data,
                                                                        "usernames" => $usernames,
                                                                        "weekdays" => $weekdays,
                                                                        "uploadfieldid" => $uploadfieldid,
                                                                        "projectfieldid" => $projectfieldid,
                                                                        "titlefieldid" => $titlefieldid,
                                                                        "descfieldid" => $descfieldid,
                                                                        "view" => $view,
                                                                        "user_is_admin" => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->userHasRole("admin"),
                                                                    ]);
        } else {
            return $twig->render("forms-media-grid/media-grid-error.html");
        }
    }

    /**
     * AJAX
     * 
     * Downloads a File
     * 
     * @return FileStream
     */
    public function downloadFile() {
        if(isset($_POST['fileid']) && trim($_POST['fileid']) != "" && is_numeric($_POST['fileid']) && get_post_type($_POST['fileid']) === "attachment") {

            $fileid = $_POST['fileid'];
            $filepost = wp_get_attachment_url($fileid);

            if(!$filepost) {
                echo "404";
                wp_die();
            }

            $file_url  = stripslashes(trim($filepost));
            $file_name = basename($filepost);

            header("Content-Disposition:attachment; filename={$file_name}");
            header("Content-Type: application/force-download");

            readfile("{$file_url}");

        } else {
            echo "0";
        }
        wp_die();
    }

    /**
     * AJAX
     * 
     * Returns Details of a file
     * 
     * @return HTML-Code
     */
    public function getDetails() {
        if(isset($_POST['fileid']) && trim($_POST['fileid']) != "" && is_numeric($_POST['fileid']) && get_post_type($_POST['fileid']) === "attachment") {

            $fileid = $_POST['fileid'];
            $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

            $fileid = $_POST['fileid'];
            $path = wp_get_attachment_url($fileid);
            $filename = basename($path);
            $pathinfo = pathinfo($path);
            
            $type = "other";
            $mediatype = "";
            switch(strtolower($pathinfo['extension'])) {
                case "mp3":
                    $type = "audio";
                    $mediatype = "audio/mpeg";
                    break;
                case "m4a":
                    $type = "audio";
                    $mediatype = "audio/m4a";
                case "wav":
                    $type = "audio";
                    $mediatype = "audio/wav";
                    break;

                case "png":
                case "jpg":
                case "jpeg":
                    $type = "image";
                    break;

                case "mp4":
                    $type = "video";
                    $mediatype = "video/mp4";
                    break;
            }

            echo $twig->render("forms-media-grid/media-grid-details.html", ["type" => $type, "mediatype" => $mediatype, "path" => $path, "filename" => $filename]);

        } else {
            echo "0";
        }
        wp_die();
    }

    /**
     * AJAX
     * 
     * Deletes a file and the corresponding FormData
     * 
     * @return 0 on failure/ 1 on success
     */
    public function deleteFile() {
        if(isset($_POST['fileid']) && is_numeric($_POST['fileid']) && isset($_POST['dataid']) && is_numeric($_POST['dataid'])) {

            $fileid = sanitize_text_field($_POST['fileid']);
            $dataid = sanitize_text_field($_POST['dataid']);
            
            $formdata = Trainingssystem_Plugin_Database::getInstance()->Formdata->getFormData($dataid);

            $usermodus = false;
            $uid = get_current_user_id();
            $selectui = '' . get_user_meta(wp_get_current_user()->ID, 'coach_select_user', true);
            if ($selectui != '') {
                $uid = $selectui;
                $usermodus = true;
            }

            if($formdata != null && !$usermodus && strcmp($formdata->getData(), $fileid) === 0 && 
                ($formdata->getUserId() == $uid || Trainingssystem_Plugin_Module_Berechtigung::getInstance()->userHasRole("admin"))) {

                if(Trainingssystem_Plugin_Database::getInstance()->Formdata->deleteSavepoint($formdata->getUserId(), $formdata->getSaveDate()) &&       
                        wp_delete_attachment($fileid, true)) {
                    echo "1";
                } else {
                    echo "2";
                }

            } else {
                echo "403";
            }

        } else {
            echo "0";
        }
        wp_die();
    }

    /**
     * AJAX
     * 
     * Deletes a project and the corresponding files and FormDatas
     * 
     * @return 0 on failure/ 1 on success
     */
    public function deleteProject() {
        if(isset($_POST['projectname']) && 
            isset($_POST['uploadfieldid']) && is_numeric($_POST['uploadfieldid']) && 
            isset($_POST['projectfieldid'])) {

            $projectname = trim($_POST['projectname']) != "" ? sanitize_text_field($_POST['projectname']) : "";
            $uploadfieldid = sanitize_text_field($_POST['uploadfieldid']);
            $projectfieldid = trim($_POST['projectfieldid']) != "" && is_numeric($_POST['projectfieldid']) ? sanitize_text_field($_POST['projectfieldid']) : '';

            $usermodus = false;
            $uid = get_current_user_id();
            $selectui = '' . get_user_meta(wp_get_current_user()->ID, 'coach_select_user', true);
            if ($selectui != '') {
                $uid = $selectui;
                $usermodus = true;
            }

            if(!$usermodus) {
                $formdata = Trainingssystem_Plugin_Database::getInstance()->Formdata->getMediaGridDataByProjectname($uid, $projectname, $projectfieldid, $uploadfieldid);

                $failure = false;
                
                foreach($formdata as $fd) {
                    if(($fd->getUserId() == $uid || Trainingssystem_Plugin_Module_Berechtigung::getInstance()->userHasRole("admin"))) {
                        if($fd->getFieldId() == $uploadfieldid) {
                            if(!wp_delete_attachment($fd->getData(), true)) {
                                $failure = true;
                            }
                        }
                        if(!Trainingssystem_Plugin_Database::getInstance()->Formdata->deleteFormData($fd->getDataId())) {
                            $failure = true;
                        }
                    } else {
                        echo "403";
                        return;
                    }
                }

                if($failure) {
                    echo "0";
                } else {
                    echo "1";
                }

            } else {
                echo "401";
            }

        } else {
            echo "0";
        }
        wp_die();
    }
}