<?php
    class Upload{

        private $db;
        private $settings;
        private $lang;
        public function __construct(){
            $this->db = new database();
            $this->settings = $_SESSION['app_2'];
            $this->lang = $_SESSION['app_2']['lang'];
        }

        public function fileUpload($name,$size,$tmp,$username,$upgrade,$max_size){
            $allow_format = $this->settings['extensions'];
            

            $array_format = explode('.',$name);
            $format = end($array_format);
            $format_check = strtolower($format);

            $name = "";
            for($i=0;$i<count($array_format)-1;$i++) $name .= $array_format[$i].".";
            $name .= $format_check;
            
            $msg = '';
            if(!in_array($format_check,$allow_format) && !empty($name)) {
                $msg = $this->lang['upload_1']." <strong> '".$name."'</strong>";
            }
            

            // Check Size
            
            if($size > $max_size * 1024 * 1024){
                $msg ="Max size $max_size MB";
            }
            $size = GetSize($size);
            
            if($msg==''){
                $code = GetLastId($this->db->con,"files");
                $code = substr(md5($name),0,5).code62($code);
                $invisible_code=GenerateALpha(5);
                $namefile = $code . $invisible_code . '.' .$format_check;
                // upload file
                $target = "../res/rsc_upload/files/".basename($namefile);
                if(move_uploaded_file($tmp,$target)){
                    $name = Remove_er_sql(str_replace(" ","-",$name));
                    $uploaded = date("Y-m-d");
                    $file_link = $this->settings['HTTP_s']."/".$code;
                    $col = array("username","alias","name","namefile","link","size","last_download","uploaded","plan");
                    $val = array($username,$code,$name,$namefile,$file_link,$size,$uploaded,$uploaded,$upgrade);
                    $this->db->Insert("files",$col,$val);
                    $this->db->Incerement("users",array("total_files"),array("1"),"username",$username);
                    ShowShort($file_link,"100%");
                }else{
                    Alert($this->lang['upload_2'],"100%");
                }
            }else{
                Alert($msg,"100%");
            }
        }

        public function fileUploadRemoteURL($file_url,$username,$upgrade,$max_size){
            $file = explode('/',$file_url);
            $name = end($file);
            $allow_format = $this->settings['extensions'];
            $array_format = explode('.',$name);
            $format = end($array_format);
            $format_check = strtolower($format);

            $name = "";
            for($i=0;$i<count($array_format)-1;$i++) $name .= $array_format[$i].".";
            $name .= $format_check;
            
            $msg = '';
            if(!in_array($format_check,$allow_format) && !empty($name)) {
                $msg = $this->lang['upload_1']." <strong> '".$name."'</strong>";
            }

            // Check Size
            $size = fileSizeURL($file_url);
            if($size > $max_size * 1024 * 1024){
                $msg ="Max size $max_size MB";
            }
            $size = GetSize($size);

            if($msg==''){
                $code = GetLastId($this->db->con,"files");
                $code = substr(md5($name),0,5).code62($code);
                $invisible_code=GenerateALpha(5);
                $namefile = $code . $invisible_code . '.' .$format_check;
                $path = "../res/rsc_upload/files/".$namefile; 
                $file = file_get_contents($file_url);
                if(file_put_contents($path,$file)){
                    $name = Remove_er_sql(str_replace(" ","-",$name));
                    $uploaded = date("Y-m-d");
                    $file_link = $this->settings['HTTP_s']."/".$code;
                    $col = array("username","alias","name","namefile","link","size","last_download","uploaded","plan");
                    $val = array($username,$code,$name,$namefile,$file_link,$size,$uploaded,$uploaded,$upgrade);
                    $this->db->Insert("files",$col,$val);
                    $this->db->Incerement("users",array("total_files"),array("1"),"username",$username);
                    ShowShort($file_link,"100%");
                }else{
                    Alert($this->lang['upload_2'],"100%");
                }
            }else{
                Alert($msg,"100%");
            }

            
        }

        public function showFiles($username){
            $result = $this->db->Query("SELECT * FROM files WHERE username='$username'");
            $number = 1;
            while($data = mysqli_fetch_array($result))  
            {  
                echo "<tr>";
                echo "<td style='min-width:5%'>".$number."</td>";
                echo "<td style='width:27%'><a style='text-decoration:none' target='_blank' href='".$data["link"]."'>".Show4char($data["name"],50)."</a></td>";
                echo "<td style='width:15%'>".$data["size"]."</td>";
                echo "<td style='width:13%'>".$data["uploaded"]."</td>";
                echo "<td style='width:10%'>".$data["download"]."</td>";
                echo "<td style='width:15%'>".$this->settings['currency'].$data["earnings_total"]."</td>";
                $id = $data['id'];
                echo "<td style='width:15%'><button class='btn btn-danger btn-sm' type='button' onclick='Confi($id)'>Delete</button></td>";
                echo "</tr>";
                $number++;
            }  
           
        }

        public function delete($id,$username){
            $req  = $this->db->Query("SELECT * FROM files WHERE id='$id' AND username='$username'");
            $rows = mysqli_num_rows($req);
            if($rows > 0 ){
                $data = mysqli_fetch_array($req);
                $file = $data['namefile'];
                $this->db->Delete("files","id",$id);
                $this->db->Incerement("users",array("total_files"),array(-1),"username",$username);
                unlink("../res/rsc_upload/files/".$file);
            }

        }

        public function getDownload($p,$ip){
            $res = array();
            // $res == [username, name, nameFile, download, size, isVisitedByIP ,referral ,Plan ]
            // $res == [    0   ,   1 ,     2   ,    3    ,  4  ,       5       ,   6     ,  7  ]

            $result = $this->db->Query("SELECT * FROM files WHERE alias = '$p'");
            $data = mysqli_fetch_assoc($result);
            $row = mysqli_num_rows($result);
            if($row == 0) {
                Redirect("404");
            }
            $user = $data['username'];

            $res [] = $user;
            $res [] = $data['name'];
            $res [] = $data['namefile'];
            $res [] = $data['download'];
            $res [] = $data['size'];

            $result = $this->db->Query("SELECT * FROM visitor WHERE ip = '$ip'");
            $rows = mysqli_num_rows($result);
            if($rows < $this->settings['VisitPerIpParDay']) $res[] ="0";
            else $res[] ="1";

            if($user != "-"){
                $result = $this->db->Query("SELECT referral FROM users WHERE username= '$user'");
                $rows = mysqli_num_rows($result);
                $dr = mysqli_fetch_assoc($result);
                if($rows == 0 ) $res[] ="noReferral";
                else $res[] = $dr['referral'];
            }
            else $res[] ="noReferral";
            $res [] = $data['plan'];
            

            return $res;

        }

        public function addDownload($alias,$username,$cpm,$eCPM,$ip,$country,$refe){
            $d = date("d-m-Y");
            // update static file
            $col_name = array("download","earnings_total");
            $value = array(1,$cpm);
            $this->db->Incerement("files",$col_name,$value,"alias",$alias);
            $this->db->Update("files",array("last_download"),array(date("Y-m-d")),"alias",$alias);
            // update static user
            $col_name = array("balance","balance_today","balance_month","total_download");
            $value = array($cpm,$cpm,$cpm,1);
            $this->db->Incerement("users",$col_name,$value,"username",$username);
            //Referral
            if($refe !="noReferral"){
                $cost = ($cpm * $this->settings['ReferralRate']) / 100;
                $this->db->Incerement("users",array("balance_ref"),array($cost),"username",$refe);
                $this->db->Incerement("reportsday",array("referrals","total"),array($cost,$cost),"username",$refe);
            }
            // update static Report
            $newCPM='cpm / 2 + '.$eCPM;
            $this->db->Query("UPDATE reportsday SET download=download+'1' ,earnings_download=earnings_download+'$cpm' ,cpm=earnings_download/download * '1000' ,total=total+'$cpm' WHERE username='$username'");
            
            // update table visitor
            $source = $_SESSION['source'];
            $this->db->Insert("visitor",array("ip","alias","source","date","country"),array($ip,$alias,$source,$d,$country));
            unset($_SESSION['source']);
            //unset($_SESSION['cpt_files']);
        }

        public function addNonDownload($alias,$cpm,$eCPM,$ip,$country){
            $d = date("d-m-Y");
            // update static Report
            $newCPM='cpm / 2 + '.$eCPM;
            $this->db->Query("UPDATE reportsnonview SET download=download+'1' ,earnings_download=earnings_download+'$cpm' ,cpm=earnings_download/download * '1000' ,total=total+'$cpm' WHERE date='$d'");
            // update table visitor
            $source = $_SESSION['source'];
            $this->db->Insert("visitor",array("ip","alias","source","date","country"),array($ip,$alias,$source,$d,$country));
            unset($_SESSION['source']);
           
        }

        public function downloadFile($file,$name){
            $fileName = basename($file);
            $filePath = '../../res/rsc_upload/files/'.$fileName;
            $_SESSION['cpt_files']=0;

            if(!empty($fileName) && file_exists($filePath)){
                // Define headers
                header("Cache-Control: public");
                header("Content-Description: File Transfer");
                header("Content-Disposition: attachment; filename=".basename($name));
                header("Content-Type: application/zip");
                header("Content-Transfer-Encoding: binary");
                
                // Read the file
                readfile($filePath);
                exit;
            }
            //exit;
        }

    }
?>