<?php

namespace App\System\Controller;
use App\System\Basic\beContoller;
use App\System\Model\AttachmentModel;
use App\System\Vendor\Auth;
use App\System\Vendor\beLanguage;
use App\System\Vendor\beUpload;

class FileController extends beContoller {
    public function add(){
        return beGetView("admin.file.add");
    }
    public function upload_post(){
        $user = Auth::beGetUser();
        $secret = (int)$_POST["secret"] == 1 ? true:false;
        $files = $_FILES["files"];
        $filecount = count($files["size"]);
        $uploads = [];
        for($i = 0; $i < $filecount; $i++){
            $file = [
                "name" => $files["name"][$i],
                "size" => $files["size"][$i],
                "type" => $files["type"][$i],
                "error" => $files["error"][$i],
                "tmp_name" => $files["tmp_name"][$i],
            ];
            $name = $file["name"];
            $slug = beSelfLink($file["name"]);
            $secretname = "";
            if($secret){
                $secretname = date("m.Y",BE_TIME)."-".substr(md5(BE_TIME),0,8)."-"."berk.diyo";
            }
            $upload = beUpload::beUploadFile($file,$secretname,BE_APPPATH."resources/upload",0,[],false);
            if(!$upload["status"]){
                $uploads[$i] = [
                    "status" => false,
                    "message" => $upload["message"]
                ];
                continue;
            }
            $aid = AttachmentModel::beInsert([
                "uid" => $user["uid"],
                "aname" => $name,
                "aslug" => $slug,
                "atype" => $file["type"],
                "asize" => $file["size"],
                "apath" => "resources/upload/".$upload["filename"],
                "aviews" => 0,
                "adownloads" => 0,
                "astatus" => "1",
                "afavorite" => "0",
                "apassword" => "",
                "adateline" => BE_TIME
            ]);
            $fileurl = beGetRoute("file.show",["aid" => $aid,"slug" => $slug]);
            $fileclassicurl = beGetConfig("siteurl")."/app/resources/upload/".$upload["filename"];
            $uploads[$i] = [
                "status" => true,
                "aid" => $aid,
                "message" => $upload["message"],
                "fileurl" => $fileurl,
                "fileclassicurl" => $fileclassicurl,
            ];
        }
        return beAjaxSuccess(["message" => "Dosyalar yükleme işlemleri tamamlandı","uploads" => $uploads]);
    }
    public function list(){
        $defaultextensions = beUpload::beDefaultExtensions;
        return beGetView("admin.file.list",["defaultextensions" => $defaultextensions]);
    }
    public function search_post(){
        beLanguage::beReadLang("user");
        $sort = (int)$_POST["sort"];
        if(!$sort){
            $sort = 1;
        }
        $page = (int)$_POST["page"];
        if(!$page){
            $page = 1;
        }
        $name = $_POST["name"];
        $type = $_POST["type"];
        $uid = (int)$_POST["user"];
        $user = [];
        if($uid){
            $user = Auth::beGetUser($uid,"uid");
            if(!$user){
                return beAjaxError(["message" => beGetLang("user_not_found")]);
            }
        }
        $itemsearch = AttachmentModel::beSelect("COUNT(aid) as total");
        if($uid){
            $itemsearch = $itemsearch->beWhere("uid",$uid);
        }
        if($name){
            $itemsearch = $itemsearch->beWhere("aname",$name,"LIKE");
        }
        if($type){
            $itemsearch = $itemsearch->beWhere("atype",$type);
        }
        $itemcount = (int)$itemsearch->beGet()["total"];
        $paganation = bePaganation($page,$itemcount,"");
        $items = AttachmentModel::beTable("be_attachments as a")->beSelect("a.*,u.name,u.surname");
        if($uid){
            $items = $items->beWhere("a.uid",$uid);
        }
        if($name){
            $items = $items->beWhere("aname",$name,"LIKE");
        }
        if($type){
            $items = $items->beWhere("atype",$type);
        }
        if($paganation["itemstart"] == 0){
            $items = $items->beLimit($paganation["itemlimit"]);
        }
        else{
            $items = $items->beLimit($paganation["itemstart"],$paganation["itemlimit"]);
        }
        $orderkey = "aid";
        switch($sort){
            case 1 :
                $items = $items->beOrder($orderkey,"DESC");
                break;
            case 2 :
                $items = $items->beOrder($orderkey,"ASC");
                break;
        }
        $items = $items->beJoin("INNER JOIN be_users as u ON u.uid = a.uid")->beGetAll();
        $itemhtml = beGetView("admin.file.listrows",["items" => $items]);
        return beAjaxSuccess(["html" => $itemhtml,"paganation" => $paganation["paganation"],"itemcount" => $itemcount]);
    }
    public function upload(){
        beLanguage::beReadLang("upload");
        $user = Auth::beGetUser();
        $file = $_FILES["file"];
        if(!$file){
            return beAjaxError(["message" => beGetLang("file_empty")]);
        }
        $name = $file["name"];
        $slug = beSelfLink($name);
        $secretname = date("m.Y",BE_TIME)."-".substr(md5(BE_TIME),0,8)."-"."berk.diyo";
        $upload = beUpload::beUploadFile($file,$secretname,BE_APPPATH."resources/upload",0,[],false);
        if(!$upload["status"]){
            return beAjaxError(["message" => $upload["message"]]);
        }
        $aid = AttachmentModel::beInsert([
            "uid" => $user["uid"],
            "aname" => $name,
            "aslug" => $slug,
            "atype" => $file["type"],
            "asize" => $file["size"],
            "apath" => "resources/upload/".$upload["filename"],
            "aviews" => 0,
            "adownloads" => 0,
            "astatus" => "1",
            "afavorite" => "0",
            "apassword" => "",
            "adateline" => BE_TIME
        ]);
        return beAjaxSuccess(["message" => beGetLang("file_uploaded_successfully"),"aid" => $aid]);
    }
    public function delete(){
        beLanguage::beReadLang("upload");
        $user = Auth::beGetUser();
        $aid = (int)$_POST["aid"];
        $file = AttachmentModel::beSelect("aid,apath")->beWhere("aid",$aid)->beWhere("uid",$user["uid"])->beGet();
        if(!$file){
            return beAjaxError(["message" => beGetLang("file_not_found")]);
        }
        unlink(BE_APPPATH.$file["apath"]);
        AttachmentModel::beDelete()->beWhere("aid",$file["aid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("file_deleted_successfully")]);
    }
    public function show($slug = "",$aid = 0){
        beLanguage::beReadLang("upload");
        $attachment = AttachmentModel::beSelect("aid,aname,atype,asize,apath,aviews,adownloads")->beWhere("aid",$aid)->beWhere("aslug",$slug)->beGet();
        if(!$attachment){
            beError("Bulunamadı",beGetLang("file_not_found"));
        }
        $this->showcontent($attachment);
    }
    public function showspecial($aid = 0){
        beLanguage::beReadLang("upload");
        $user = Auth::beGetUser();
        $attachment = AttachmentModel::beSelect("aid,aname,atype,asize,apath,aviews,adownloads")->beWhere("aid",$aid)->beWhere("uid",$user["uid"])->beGet();
        if(!$attachment){
            beError("Bulunamadı",beGetLang("file_not_found"));
        }
        $this->showcontent($attachment);
    }
    public function showcontent($attachment){
        if($_GET["action"] != "download"){
            switch($attachment["atype"]){
                case "application/pdf":
                case "image/bmp":
                case "image/gif":
                case "image/webp":
                case "image/jpeg":
                case "image/pjpeg":
                case "image/png":
                case "text/html":
                    header("Content-type: {$attachment['atype']}");
                    $disposition = "inline";
                    break;
                default:
                    $filetype = $attachment["atype"];
                    if(!$filetype){
                        $filetype = "application/force-download";
                    }
                    header("Content-type: {$filetype}");
                    $disposition = "attachment";
                    break;
            }  
        }
        else{
            $filetype = "application/force-download";
            header("Content-type: {$filetype}");
            $disposition = "attachment";		
        }
        if(strpos(strtolower($_SERVER["HTTP_USER_AGENT"]),"msie") !== false){
            header("Content-disposition: attachment; filename=\"{$attachment['aname']}\"");
        }
        else{
            header("Content-disposition: {$disposition}; filename=\"{$attachment['aname']}\"");
        }
        if(strpos(strtolower($_SERVER["HTTP_USER_AGENT"]),"msie 6.0") !== false){
            header("Expires: -1");
        }
        header("Content-length: {$attachment['asize']}");
        header("Content-range: bytes=0-".($attachment["asize"]-1)."/".$attachment["asize"]);
        $filehandle = fopen(BE_APPPATH.$attachment["apath"],"rb");
        while(!feof($filehandle)){
            echo fread($filehandle,8192);
        }
        fclose($filehandle);
        if($disposition == "attachment"){
            AttachmentModel::beUpdate(["adownloads" => $attachment["adownloads"]+1])->beWhere("aid",$attachment["aid"])->beExecute();
        }
        else{
            AttachmentModel::beUpdate(["aviews" => $attachment["aviews"]+1])->beWhere("aid",$attachment["aid"])->beExecute();
        }
        exit;
    }
}

?>