<?php
    class Admin{
        private $db;
        private $settings;
        public function __construct(){
            $this->db = new database();
            $this->settings = $_SESSION['app_2'];
        }

        public function AdminLogin($admin,$password){
            $admin = Remove_er_sql(strtolower($admin));
            $password = Remove_er_sql(strtolower($password));
            
            
            $debug = array();
            if(empty($admin)){
                array_push($debug,"admin is required");
            }
            if(empty($password)){
                array_push($debug,"Password is required");
            }

            if(count($debug) == 0){
                $password = md5($password);
                $result = $this->db->Query("SELECT * FROM admin WHERE name='$admin' AND password='$password'");
                $row=mysqli_fetch_array($result);
                $check = mysqli_num_rows($result);
                if($check == 0){
                    array_push($debug,"invalid admin and password ! try again");
                }else{
                    
                    if($row['status'] =='block'){
                        array_push($debug,"Your account has been blocked");
                    }else{
                        $_SESSION['app_2']['admin_login']=true;
                        $_SESSION['app_2']['admin'] = $admin;
                        
                        Redirect("area/dashboard");
                    }
                    
                }
            }
            return $debug;
        }

        public function newAdmin($admin,$pass1,$pass2){ 
            if($this->settings['demo'] == false ){
                $admin = Remove_er_sql(strtolower($admin));
                $pass1 = Remove_er_sql(strtolower($pass1));
                $pass2 = Remove_er_sql(strtolower($pass2));
                

                $debug = array();
                if(empty($admin) || strlen($admin) < 5) array_push($debug,"Username is Required And Minimum Length 5");
                if(empty($pass1) || strlen($pass1) < 5) array_push($debug,"Password is Required And Minimum Length 5");
                if($pass1 != $pass2) array_push($debug,"The two passwords do not match");
                
                if($this->db->isExists("admin","name",$admin) == true){
                    array_push($debug,"Admin already exists");
                }
                
                if(count($debug) == 0){
                
                    $pass1 = md5($pass1);
                    $date_reg = date("Y-m-d");
                    $col = array("name","password","reg_day","lvl");
                    $val = array($admin,$pass1,$date_reg,"0");
                    $this->db->Insert("admin",$col,$val);
                    Success("New admin has been added","100%");
                }else{
                    for($i=0;$i<count($debug);$i++){
                        Alert($debug[$i],"100%");
                    }
                }
            }
            else Alert("This request is disabled into demo mode.","100%");

            
        }

        public function logout(){
            $_SESSION['app_2']['adminlogin']=false;
            session_destroy();
            unset($_SESSION['app_2']['admin']);
		    header("location: home");
            exit();
        }

        // Page USERS
        public function showAllUsers(){
            $result = $this->db->Query("SELECT id,username,balance,balance_today,login_day,login_day_ip,reg_ip FROM users WHERE status!='block'");
            while($data = mysqli_fetch_array($result)){
                echo "<tr>";
                echo "<td style='width:5%'>".$data['id']."</td>";
                echo "<td style='width:14%'>".$data['username']."</td>";
                echo "<td style='width:10%'>".$this->settings['currency'].$data['balance']."</td>";
                echo "<td style='width:10%'>".$this->settings['currency'].$data['balance_today']."</td>";
                echo "<td style='width:12%'>".$data['login_day']."</td>";
                echo "<td style='width:12%'>".$data['login_day_ip']."</td>";
                $id = $data['id'];
                echo "<td style='width:25%'>
                        <button class='btn btn-info btn-sm' type='button' onclick='fun1($id)'>View</button>
                        <button class='btn btn-success btn-sm' type='button' onclick='edit($id)'>Edit</button>
                        <button class='btn btn-danger btn-sm' type='button' onclick='block($id)'>block</button> 
                        <button class='btn btn-warning btn-sm' type='button' onclick='dlt($id)'>Delete</button>
                
                </td>";
                echo "</tr>";
            }
        }

        public function showUser($id){
            $result = $this->db->Query("SELECT * FROM users WHERE id='$id'");
            $row=mysqli_fetch_array($result);
            $check = mysqli_num_rows($result);
            if($check == 1){
                if($row["upgrade"] == "0") $plan = "Free";
                if($row["upgrade"] == "1") $plan = "Plus";
                if($row["upgrade"] == "2") $plan = "Pro";
                echo '
                    <h6 class="tile-title">User ID :'.$id.'</h6>
                    <table class="table table-bordered table-hover">
                    <tbody>
                        <tr>
                            <td>Status</td>
                             <td>'.$row["status"].'</td>
                        </tr>
                    
                        <tr>
                            <td>Username</td>
                            <td>'.$row["username"].'</td>
                        </tr>

                        <tr>
                            <td>Email</td>
                            <td>'.$row["email"].'</td>
                        </tr>

                        <tr>
                            <td>Plan</td>
                            <td>'.$plan.'</td>
                        </tr>

                        <tr>
                            <td>Plan Expiration Date</td>
                            <td>'.$row["upgrade_finish"].'</td>
                        </tr>

                        <tr>
                            <td>Balance</td>
                            <td>'.$this->settings['currency'].$row["balance"].'</td>
                        </tr>

                        <tr>
                            <td>Earnings Today</td>
                            <td>'.$this->settings['currency'].$row["balance_today"].'</td>
                        </tr>

                        <tr>
                            <td>Earnings This Month</td>
                            <td>'.$this->settings['currency'].$row["balance_month"].'</td>
                        </tr>

                        <tr>
                            <td>Referral Earnings</td>
                            <td>'.$this->settings['currency'].$row["balance_ref"].'</td>
                        </tr>

                        <tr>
                            <td>Total Files</td>
                            <td>'.$row["total_files"].'</td>
                        </tr>

                        <tr>
                            <td>Total download</td>
                            <td>'.$row["total_download"].'</td>
                        </tr>

                        <tr>
                            <td>Last Login</td>
                            <td>'.$row["login_day"].'</td>
                        </tr>

                        <tr>
                            <td>Last login ip</td>
                            <td>'.$row["login_day_ip"].'</td>
                        </tr>

                        <tr>
                            <td>Register IP</td>
                            <td>'.$row["reg_ip"].'</td>
                        </tr>

                        <tr>
                            <td>Register Day</td>
                            <td>'.$row["reg_day"].'</td>
                        </tr>

                        <tr>
                            <td>Referred by</td>
                            <td>'.$row["referral"].'</td>
                        </tr>

                        <tr>
                            <td>date Referral</td>
                            <td>'.$row["date"].'</td>
                        </tr>

                        <tr>
                            <td>payment method</td>
                            <td>'.$row["payment_type"].'</td>
                        </tr>

                        <tr>
                            <td>payment Account</td>
                            <td>'.$row["payment_account"].'</td>
                        </tr>

                        <tr>
                            <td>payment pending</td>
                            <td>'.$this->settings['currency'].$row["pending_payment"].'</td>
                        </tr>

                        <tr>
                            <td>payment total</td>
                            <td>'.$this->settings['currency'].$row["total_payment"].'</td>
                        </tr>


                    </tbody>
                ';
            }

        }

        public function showEditUser($id){
            $result = $this->db->Query("SELECT * FROM users WHERE id='$id'");
            $row=mysqli_fetch_array($result);
            $check = mysqli_num_rows($result);
            if($check == 1){
                if($row["upgrade"] == "0") $plan = "Free";
                elseif($row["upgrade"] == "1") $plan = "Plus";
                elseif($row["upgrade"] == "2") $plan = "Pro";
                if($row["upgrade_finish"] != "" || $row["upgrade_finish"] != null)
                $expiration = 'value="'.$row["upgrade_finish"].'"';
                else
                $expiration = 'placeholder="dd-mm-yyyy"';
                
                echo '
                    <h6 class="tile-title">User ID :'.$id.'</h6>
                    <table class="table table-bordered table-hover">
                    <tbody>
                        <tr>
                            <td>Username</td>
                            <td><input class="form-control" type="text" style="width:50%" value="'.$row["username"].'" Disabled></td>
                        </tr>
                        
                        <tr>
                            <td>Email</td>
                            <td><input class="form-control" type="text" style="width:50%" name="email" value="'.$row["email"].'" ></td>
                        </tr>

                        <tr>
                            <td>Plan</td>
                            <td>
                                <select class="form-control" name="plan" style="width:50%">
                                    <option value="'.$row["upgrade"].'">---'.$plan.'---</option>
                                    <option value="0">Free</option>
                                    <option value="1">Plus</option>
                                    <option value="2">Pro</option>
                                </select>
                            </td>
                        </tr>

                        <tr>
                            <td>Plan Expiration Date</td>
                            <td><input class="form-control" type="text" style="width:50%" name="expiration" '.$expiration.' ></td>
                        </tr>

                        <tr>
                            <td>Balance ('.$this->settings['currency'].')</td>
                            <td><input class="form-control" type="text" style="width:50%" name="balance" value="'.$row["balance"].'"></td>
                        </tr>

                        <tr>
                            <td>Earnings Today</td>
                            <td><input class="form-control" type="text" style="width:50%" name="balance_today" value="'.$row["balance_today"].'"></td>
                        </tr>

                        <tr>
                            <td>Earnings This Month</td>
                            <td><input class="form-control" type="text" style="width:50%" name="balance_month" value="'.$row["balance_month"].'"></td>
                        </tr>

                        <tr>
                            <td>Referral Earnings</td>
                            <td><input class="form-control" type="text" style="width:50%" name="balance_ref" value="'.$row["balance_ref"].'"></td>
                        </tr>

                        <tr>
                            <td></td>
                            <td><input class="btn btn-success" type="submit" name="submit" value="Update"></td>
                        </tr>

                    </tbody>
                    </table>
                ';
            }

        }

        public function EditUser($id,$data){
            $col = array("email","balance_ref","balance","balance_today","balance_month","upgrade","upgrade_finish");
            $this->db->Update("users",$col,$data,"id",$id);
            Success("User has been updated","100%");
        }

        public function selectAllUsers(){
            $res = $this->db->Query("SELECT * FROM users WHERE status='on'");
            while($data = mysqli_fetch_array($res)){
                echo "<option value=".$data['username'].">".$data['username']."</option>";
            }
        }

        public function showBlockUsers(){
            $result = $this->db->Query("SELECT id,username,balance,balance_today,login_day,login_day_ip,reg_ip FROM users WHERE status='block'");
            while($data = mysqli_fetch_array($result)){
                echo "<tr>";
                echo "<td style='min-width:5%'>".$data['id']."</td>";
                echo "<td style='width:14%'>".$data['username']."</td>";
                echo "<td style='width:10%'>".$this->settings['currency'].$data['balance']."</td>";
                echo "<td style='width:10%'>".$this->settings['currency'].$data['balance_today']."</td>";
                echo "<td style='width:12%'>".$data['login_day']."</td>";
                echo "<td style='width:12%'>".$data['login_day_ip']."</td>";
                echo "<td style='width:12%'>".$data['reg_ip']."</td>";
                $id = $data['id'];
                echo "<td style='width:25%'>
                        <button class='btn btn-info btn-sm' type='button' onclick='fun1($id)'>View</button>
                        <button class='btn btn-primary btn-sm' type='button' onclick='active($id)'>Active</button> 
                        <button class='btn btn-warnnig btn-sm' type='button' onclick='dlt($id)'>Delete</button>
                
                </td>";
                echo "</tr>";
            }
        }

        public function allReferrals(){
            $result = $this->db->Query("SELECT id,username,referral,date FROM users WHERE referral!='-'");
            while($data = mysqli_fetch_array($result)){
                echo "<tr>";
                echo "<td style='min-width:5%'>".$data['id']."</td>";
                echo "<td style='width:30%'>".$data['username']."</td>";
                echo "<td style='width:30%'>".$data['referral']."</td>";
                echo "<td style='width:35%'>".$data['date']."</td>";

                echo "</tr>";
            }
        }

        public function showAllPremium(){
            $result = $this->db->Query("SELECT id,username,upgrade,upgrade_start,upgrade_finish FROM users WHERE upgrade!='0'");
            while($data = mysqli_fetch_array($result)){
                echo "<tr>";
                echo "<td style='min-width:5%'>".$data['id']."</td>";
                echo "<td style='width:20%'>".$data['username']."</td>";
                if($data['upgrade'] == "1") $plan = "Plus";
                elseif($data['upgrade'] == "2") $plan = "Pro";
                echo "<td style='width:10%'>".$plan."</td>";
                echo "<td style='width:30%'>".$data['upgrade_start']."</td>";
                echo "<td style='width:35%'>".$data['upgrade_finish']."</td>";

                echo "</tr>";
            }
        }

        public function deleteUser($user_id){
            if($this->settings['demo'] == false ){
                $this->db->Delete("users","id",$user_id);
            }
            else Alert("This request is disabled into demo mode.","100%");
        }

        public function blockUser($user_id){
            if($this->settings['demo'] == false ){
                $this->db->Update("users",array("status"),array("block"),"id",$user_id);
                // Block all His Links and files 
            }
            else Alert("This request is disabled into demo mode.","100%");
            
        }

        public function ActiveUser($user_id){
            $this->db->Update("users",array("status"),array("on"),"id",$user_id);
            // Active all His Links and files 
        }

        // Manager Files
        public function showAllFiles(){
            if($this->settings['ShowAllFiles'] == "no"){
                $result = $this->db->Query("SELECT * FROM files where username !='-'");
            }else{
                $result = $this->db->Query("SELECT * FROM files");
            }
            
            while($data = mysqli_fetch_array($result)){
                $id = $data['id'];
                $username = $data['username'];
                echo "<tr>";
                echo "<td style='width:5%'>". $id."</td>";
                echo "<td style='width:15%'>".$username."</td>";
                echo "<td style='width:15%'><a href='".$data['link']."' target='_blank'>".Show4char($data['name'],25)."</a></td>";
                echo "<td style='width:8%'>".$data['size']."</td>";
                echo "<td style='width:12%'>".$data['uploaded']."</td>";
                echo "<td style='width:12%'>".$data['last_download']."</td>";
                echo "<td style='width:8%'>".$data['download']."</td>";
                echo "<td style='width:10%'>".$this->settings['currency'].$data['earnings_total']."</td>";

                $path =$data['namefile'];
                echo "<td style='width:10%'>
                    <button class='btn btn-danger btn-sm' type='button' onclick='Confi($id,\"$path\",\"$username\")'>Delete</button>
                
                </td>";
                echo "</tr>";
            }
        }

        public function delete($id,$username,$file){
            $this->db->Delete("files","id",$id);
            if($username != "-") $this->db->Incerement("users",array("total_files"),array(-1),"username",$username);
            unlink("../../res/rsc_upload/files/".$file); 
        }

        // MailBox
        public function showAllMsg(){
            $result = $this->db->Query("SELECT * FROM msg ORDER BY id DESC");
            while($data = mysqli_fetch_array($result)){
                $id = $data['id'];
                echo "<tr>";
                echo '<td><div class="animated-checkbox"><label>
                        <input type="checkbox" name="box[]" value="'.$id.'"><span class="label-text"></span>
                        </label></div>
                    </td>';
                if($data['status'] == 0) echo '<td><a href="#"><i class="fa fa-star-o"></a></td>';
                else echo '<td><a href="#"><i class="fa fa-star"></a></td>';
                echo '<td><a href="#" onclick="showMsg('.$id.')">'.$data['username'].'</a></td>';
                echo '<td class="mail-subject"><b>'.$data['subject'].'</b> <span style="color:red">'. $data['type'].'</span> - '.Show4char($data['message'],50).'</td>';
                echo '<td> '.get_time_ago($data['date']).'</td>';
                echo '</tr>';
                
            }
        }

        public function showMsg($user_id){
            $result = $this->db->Query("SELECT * FROM msg Where id='$user_id'");
            $data = mysqli_fetch_array($result);
            echo '<h4 class="mb-4 line-head" id="indicators">'.$data['subject'].' - <span style="color:#009688">'.$data['username'].'</span></h4>';
            echo $data['message'];
            $this->db->Update("msg",array("status"),array("1"),"id",$user_id);
        }

        public function deleteMsg($ar){
            if(count($ar)!=0){
                for($i=0;$i<count($ar);$i++){
                    $this->db->Delete("msg","id",$ar[$i]);
                }
            }
            
        }

        public function sendNotic($from,$title,$subject,$message,$icon,$color){
            // icon : fa-envelope,fa-hdd-o,fa-money
            //color : primary,danger,warning,success,info
            if(!empty($subject) && !empty($message) && !empty($from)){
                $col = array("user","title","subject","message","date","icon","color");
                $val = array($from,$title,$subject,$message,date("d-m-Y H:i:s"),$icon,$color);
                $this->db->Insert("notification",$col,$val);
                Success("Massage has been sent","100%");
            }
            else{
                Alert("All fields must be filled","100%");
            }
        }

        public function sendAnno($title,$subject,$message,$icon,$color){
            // icon : fa-envelope,fa-hdd-o,fa-money
            //color : primary,danger,warning,success,info
            if(!empty($subject) && !empty($message)){
                $date = date("d-m-Y H:i:s");
                $ar_users = array();
                $res = $this->db->Query("SELECT * FROM users");
                while($us = mysqli_fetch_array($res)){
                    $ar_users[] = $us['username'];
                }
                $cmd="INSERT INTO notification (user,title,subject,message,date,icon,color) 
                    VALUES ('$ar_users[0]','$title','$subject','$message','$date','$icon','$color')";
                
                for($i=1;$i<count($ar_users);$i++){
                    $cmd.=",('$ar_users[$i]','$title','$subject','$message','$date','$icon','$color')";
                }

                $this->db->Query($cmd);

                Success("Notice has been sent","100%");
            }
            else{
                Alert("All fields must be filled","100%");
            }
        }

        public function showNotic($username){
            $result = $this->db->Query("SELECT * FROM notification WHERE username='$username' AND status='0' ORDER BY id DESC");
            while($data = mysqli_fetch_array($result)){


                echo '<li><a class="app-notification__item" href="notification"><span class="app-notification__icon">
                <span class="fa-stack fa-lg"><i class="fa fa-circle fa-stack-2x text-'.$data['color'].'"></i>
                <i class="fa '.$data['icon'].' fa-stack-1x fa-inverse"></i></span></span>';
                echo '<div><p class="app-notification__message">'.$data['title'].'</p>';
                echo '<p class="app-notification__meta">'.get_time_ago($data['date']).'</p>';
                echo '</div></a></li>';

            }
        }

        public function notic_read($notic){
            $result = $this->db->Query($notic);
            while($data = mysqli_fetch_array($result)){
                getOject($data);
            }
        }

        public function notic_write($notic){
            $this->db->Query($notic);
        }

        //Dashboard
        public function showStaticPro($col,$table){
            $a = $this->db->Query("SELECT sum($col) as total FROM `$table`");
            $data = mysqli_fetch_array($a);
            return $data['total'];
        }

        public function showStatic($table){
            $a = $this->db->Query("SELECT sum($table) as total FROM users");
            $data = mysqli_fetch_array($a);
            return Show4Num($data['total'],5);
        }

        public function TotalFilesSize(){
            $total = 0; //GB
            $res = $this->db->Query("SELECT size FROM files");
            while($us = mysqli_fetch_array($res)){
                $ar = explode(' ',$us['size']);
                $type = end($ar);
                if($type == "MB") $total += $ar[0]/1024;
                elseif($type == "KB") $total += $ar[0]/(1024*1024);
                elseif($type == "B") $total += $ar[0]/(1024*1024*1024);
                
            }

            return round($total,4) . " GB";
        }

        public function getDateReport(){
            $result = $this->db->Query("SELECT * FROM reports ORDER BY id ASC Limit 1");
            $data = mysqli_fetch_array($result);
            $date_report = explode(',',$data['date']);
            return $date_report;
        }

        public function reports($page){
            $Reports = array(array(),array(),array(),array(),array());
            $date_report = $this->getDateReport();
            for($k=0;$k<count($date_report);$k++) {
                $Reports[0][] = 0;
                $Reports[1][] = 0;
                $Reports[2][] = 0;
                $Reports[3][] = 0;
                $Reports[4][] = 0;


            }
            $q = $this->db->Query("SELECT * FROM reports ORDER BY id ASC");
            while($data = mysqli_fetch_array($q)){

                $rViews = explode(',',$data['download']);
                $Reports[0] = addArray($Reports[0],array_reverse($rViews));

                $rLink = explode(',',$data['earnings_download']);
                $Reports[1] = addArray($Reports[1],array_reverse($rLink));

                $rCPM = explode(',',$data['cpm']);
                $Reports[2] = addArray($Reports[2],array_reverse($rCPM));

                $rRef = explode(',',$data['referrals']);
                $Reports[3] = addArray($Reports[3],array_reverse($rRef));

                $rTotal = explode(',',$data['total']);
                $Reports[4] = addArray($Reports[4],array_reverse($rTotal));
            }

            $date_report = array_reverse($date_report);
            $NumRowToShow = 10;
            $Start = ($page * $NumRowToShow) - $NumRowToShow;
            $End = $page * $NumRowToShow;
            if($End > count($date_report)) $End = count($date_report);
            
            for($i=$Start;$i<$End;$i++){
                echo "<tr>";
                echo "<td>".$date_report[$i]."</td>";                                   //date
                echo "<td>".$Reports[0][$i]." / ".$this->settings['currency'].$Reports[1][$i]."</td>";            //earnings_download
                echo "<td>".$this->settings['currency'].Show4Num($Reports[2][$i],4)."</td>";                      //eCPM
                echo "<td>".$this->settings['currency'].$Reports[3][$i]."</td>";                                  //Referrals
                echo "<td>".$this->settings['currency'].$Reports[4][$i]."</td>";  
                echo "</tr>";   

                
            }
            
            
        }

        public function getDataSet(){

            $Reports = array(array());
            $date_report = $this->getDateReport();
            for($k=0;$k<count($date_report);$k++) {
                $Reports[0][] = 0;
            }
            $q = $this->db->Query("SELECT download FROM reports ORDER BY id ASC");
            while($data = mysqli_fetch_array($q)){

                $rViews = explode(',',$data['download']);
                $Reports[0] = addArray($Reports[0],array_reverse($rViews));
            }
            $Reports[0] = Last_10_Days_Report(array_reverse($Reports[0]));

            //$date_report = array_reverse($date_report);
            return $Reports;
            
            
        }

        public function getTypeTraffic(){
            $Reports = array(array());
            $date_report = $this->getDateReport();
            for($k=0;$k<count($date_report);$k++) {
                $Reports[0][] = 0;
            }
            $q = $this->db->Query("SELECT download FROM reports ORDER BY id ASC");
            while($data = mysqli_fetch_array($q)){
                
                $rViews = explode(',',$data['download']);
                $Reports[0] = addArray($Reports[0],array_reverse($rViews));
            }
            $Reports[0] = Last_10_Days_Circle(array_reverse($Reports[0]));

            //$date_report = array_reverse($date_report);
            return $Reports;
        }

        // Manager ADS
        public function showAllADS(){
            $rates_ids = array();
            $result = $this->db->Query("SELECT * FROM rates WHERE status = 'on' ORDER BY id ASC");
            while($data = mysqli_fetch_array($result)){
                $style="style='width:50px;padding-left:5px'";
                $id = $data['id'];
                $rates_ids[] = $id;
                
                echo "<tr>";
                
                echo "<td style='width:3%'>".$data['id']."</td>";
                echo "<td style='width:8%'>".$data['code']."</td>";
                echo "<td style='width:20%'>".$data['country']."</td>";
                
                
                echo "<td style='width:10%'><input $style name='a11-$id' value='".$data['Pub_file']."'></td>";
                echo "<td style='width:20%'>
                        Set 0 to disable
                </td>";
                echo "</tr>";

                //$this->updateADS($id);
                
            }
            return $rates_ids;
        }

        public function updateADS($rates_ids){

            for($i=0;$i<=count($rates_ids);$i++){
                $id = $rates_ids[$i];
                $price = $_POST['a11-'.$id];
                getError($price."/".$id);
                $req = "UPDATE `rates` SET `Pub_file` = '$price' WHERE `id` = $id; ";
                $this->db->Query($req);
            }
 
            Redirect("ads");
        }
        

        // EarningReports
        public function EarningReports($date1,$date2){
            $total = array(0,0,0,0,0);
            $Reports = array(array(),array(),array(),array(),array());
            $date_report = $this->getDateReport();
            for($k=0;$k<count($date_report);$k++) {
                $Reports[0][] = 0;
                $Reports[1][] = 0;
                $Reports[2][] = 0;
                $Reports[3][] = 0;
                $Reports[4][] = 0;

            }

            $q = $this->db->Query("SELECT * FROM reports ORDER BY id ASC");
            while($data = mysqli_fetch_array($q)){

                $rViews = explode(',',$data['download']);
                $Reports[0] = addArray($Reports[0],array_reverse($rViews));

                $rLink = explode(',',$data['earnings_download']);
                $Reports[1] = addArray($Reports[1],array_reverse($rLink));

                $rCPM = explode(',',$data['cpm']);
                $Reports[2] = addArray($Reports[2],array_reverse($rCPM));

                $rRef = explode(',',$data['referrals']);
                $Reports[3] = addArray($Reports[3],array_reverse($rRef));

                $rTotal = explode(',',$data['total']);
                $Reports[4] = addArray($Reports[4],array_reverse($rTotal));
            }

            $date_report = array_reverse($date_report);
            $date1 = DateFormat($date1);
            $date2 = DateFormat($date2);

            $result = $this->db->Query("SELECT * FROM reports ORDER BY id ASC Limit 1");
            $data = mysqli_fetch_array($result);
            $date_show = explode(',',$data['date']);
            $d1 = array_search($date1, $date_show);
            $d2 = array_search($date2, $date_show);
            
            
            for($i=0;$i<count($date_report);$i++){
                if($d1 <= $i && $d2 >= $i){
                    echo "<tr>";
                    echo "<td>".$date_report[$i]."</td>";                                
                    echo "<td>".$Reports[0][$i]." / ".$this->settings['currency'].$Reports[1][$i]."</td>";
                                 
                    echo "<td>".$this->settings['currency'].Show4Num($Reports[2][$i],4)."</td>";                     
                    echo "<td>".$this->settings['currency'].$Reports[3][$i]."</td>";                                  
                    echo "<td>".$this->settings['currency'].$Reports[4][$i]."</td>";  
                    echo "</tr>";  

                    $total[0] +=$Reports[0][$i];   
                    $total[1] +=$Reports[1][$i];
                    $total[3] +=$Reports[3][$i];   
                    $total[4] +=$Reports[4][$i]; 
                } 
            }

            $total[2] = ($total[4] / $total[0]) * 1000;   


            echo "<tr style='background-color:#def3d7'>";
            echo "<td>Total</td>";                                  
            echo "<td>".$total[0]." / ".$this->settings['currency'].$total[1]."</td>";            
            echo "<td>".$this->settings['currency'].Show4Num($total[2],4)."</td>";                     
            echo "<td>".$this->settings['currency'].$total[3]."</td>";                                 
            echo "<td>".$this->settings['currency'].$total[4]."</td>";  
            echo "</tr>";
        }

        public function TopCountries(){
            $color = array("#2892A8","#46BFBD","#68CFAE","#B8E9FA","#97B8CC");
            //$color = array("#199587","#2B9DB4","#2DA847","#FCC41D","#CA2F3D");
            $pieChart = "";
            $index = 0;
            $this_month = date("m");
            $query = $this->db->Query("SELECT country,sum(qte) as qte_ FROM q_country where SUBSTRING(date,4,2) = $this_month GROUP BY country ORDER BY qte_ DESC LIMIT 5");
            while($data = mysqli_fetch_array($query)){
                $pieChart .= '{ value: '.$data['qte_'].', color: "'.$color[$index].'", highlight: "'.$color[$index].'", label: "'.$data['country'].'"}, ';
                $index++;
            }
            echo $pieChart;

        }

        // Manager Campaign
        public function CreateCampaign($name,$type,$url,$file1,$file2,$code){
            // file1 => name file
            // file2 => tmp file
            if($this->settings['demo'] == false ){
                $error = array();
                $check_error = false;
                $name = Remove_er_sql($name);
                $type = Remove_er_sql($type);

                $validationURL = Validation("Url",$url);


                if(empty($name)) $error[] = "Campaign Name is Required";
                if(empty($type)) $error[] = "Campaign Type is Required";
                if(!$validationURL) $error[] = "URL is invalid";
                
                if(count($error) == 0){
                    if(empty($code)){
                        if($file1 !=""){
                            $allow_format = array('tif','jpg','gif','png');
                            $array_format = explode('.',$file1);
                            $format = end($array_format);
        
                            if(!in_array($format,$allow_format)) {
                                $error[]= "Extension not allowed for banner <strong> '".$file1."'</strong>";
                            }else{
                                $newNameFile = GetLastId($this->db->con,"campaigns");
                                $invisible_code=GenerateALpha(3);
                                $namefile = $newNameFile .$invisible_code .'.' .$format;
                                $target = "../../res/rsc_upload/banner/".basename($namefile);
                                if(move_uploaded_file($file2,$target)){
                                    $code="--";
                                }
                            }
                        }
                        else $error[] = "Upload Banner or Html Tag";
                        
                        
                    }else{
                        $namefile="html code";
                        $url = "--";
                        //$code="waiting";
                    }

                    $col = array("adsName","adsType","Url","Banner","HtmlText");
                    $val = array($name,$type,$url,$namefile,$code);
                    
                }else{
                    for($i=0;$i<count($error);$i++){
                        Alert($error[$i],"100%");
                    }
                    $check_error = true;
                }

                if(count($error) == 0){
                    
                    // Success
                    $this->db->Insert("campaigns",$col,$val);
                    Success("Campaign Successfully Added","100%");

                }else if($check_error == false){
                    for($i=0;$i<count($error);$i++){
                        Alert($error[$i],"100%");
                    }
                }
            }
            else Alert("This request is disabled into demo mode.","100%");
        }

        public function AllCampaign(){
            $result = $this->db->Query("SELECT * FROM campaigns where adsName != 'script_0_1_0_2_6'");
            while($data = mysqli_fetch_array($result))  
            {  
                echo "<tr>";
                echo "<td style='width:5%'>".$data["id"]."</td>";
                echo "<td style='width:20%'>".$data["adsName"]."</td>";
                echo "<td style='width:10%'>".$data["adsType"]."</td>";
                echo "<td style='width:25%'><a style='text-decoration:none' target='_blank' href='".$data["Url"]."'>".Show4char($data["Url"],25)."</a></td>";
                echo "<td style='width:15%'>".$data["views"]."</td>";
                echo "<td style='width:10%'>".$data["status"]."</td>";

                $id = $data['id'];
                $path = $data['Banner'];
                echo "<td style='width:15%'>";
                if($data["status"] == "Active"){
                    echo "<button class='btn btn-warning btn-sm' type='button' onclick='inactive($id)'>Inactive</button> ";
                }else{
                    echo "<button class='btn btn-info btn-sm' type='button' onclick='active($id)'>Active</button> ";
                }  
                echo "<button class='btn btn-danger btn-sm' type='button' onclick='dlt($id,\"$path\")'>Delete</button>";

                echo "</td></tr>";

            }  
        }

        public function activeCampaign($id){
            if($this->settings['demo'] == false ){
                $this->db->Update("campaigns",array("status"),array("Active"),"id",$id);
            }
            else Alert("This request is disabled into demo mode.","100%");
        }

        public function InactiveCampaign($id){
            if($this->settings['demo'] == false ){
                $this->db->Update("campaigns",array("status"),array("Inactive"),"id",$id);
            }
            else Alert("This request is disabled into demo mode.","100%");
        }

        public function DeleteCampaign($id,$file){
            if($this->settings['demo'] == false ){
                $this->db->Delete("campaigns","id",$id);
                unlink("../../res/rsc_upload/banner/".$file);
            }
            else Alert("This request is disabled into demo mode.","100%");
        }

        // Manage Withdraws
        public function showAllWithdraws(){
            $result = $this->db->Query("SELECT * FROM payments");
            while($data = mysqli_fetch_array($result))  
            {  
                echo "<tr>";
                echo "<td style='width:5%'>".$data["id"]."</td>";
                echo "<td style='width:10%'>".$data["username"]."</td>";
                echo "<td style='width:10%'>".$data["date"]."</td>";
                echo "<td style='width:10%'>".$data["method"]."</td>";
                echo "<td style='width:10%'>".$data["account"]."</td>";
                echo "<td style='width:10%'>".$this->settings['currency'].$data["balance"]."</td>";
                echo "<td style='width:10%'>".$this->settings['currency'].$data["ref_balance"]."</td>";
                echo "<td style='width:10%'>".$this->settings['currency'].$data["amount"]."</td>";
                echo "<td style='width:10%'>".$data["status"]."</td>";

                

                echo "<td style='width:15%'>";
                if($data["status"] == "Pending"){
                    $id = $data['id'];
                    $list = array($id,$data["username"],$data["amount"]);
                    $js_array = json_encode($list);
                    echo "<button class='btn btn-info btn-sm' type='button' onclick='approve($js_array)'>Approve</button> ";
                    echo "<button class='btn btn-warning btn-sm' type='button' onclick='cancel($js_array)'>cancel</button> ";
                    echo "<button class='btn btn-danger btn-sm' type='button' onclick='return100($js_array)'>return</button>";

                }else{
                    $sts =  $data["status"];

                    echo "<button class='btn btn-type btn-sm' type='button'>$sts</button> ";
                }  
                

                echo "</td></tr>";

            }  
        }

        public function PayApprove($id,$user,$amount){
            $this->db->Update("payments",array("status"),array("Complete"),"id",$id);
            $this->db->Incerement("users",array("pending_payment"),array(-$amount),"username",$user);
            $this->db->Incerement("users",array("total_payment"),array($amount),"username",$user);
        }

        public function PayCancel($id,$user,$amount){
            $this->db->Update("payments",array("status"),array("Cancelled"),"id",$id);
            $this->db->Incerement("users",array("pending_payment"),array(-$amount),"username",$user);
        }

        public function PayReturn($id,$user,$amount){
            $this->db->Update("payments",array("status"),array("Returned"),"id",$id);
            $this->db->Incerement("users",array("pending_payment"),array(-$amount),"username",$user);
            $this->db->Incerement("users",array("balance"),array($amount),"username",$user);
        }

        //Settings
        public function EditGeneral(){
            if($this->settings['demo'] == false ){
                $SettingName = array("SiteName","SiteMetaTitle","Keywords","Des","chance","VisitPerIpParDay","Email","DurationSkipLink","HTTP_s","ReferralRate","AllowAdBlock","ShowAllFiles","currency");
                for($i=0;$i<count($SettingName);$i++){
                    $this->db->Update("setting",array("settingvalue"),array($_POST[$SettingName[$i]]),"settingName",$SettingName[$i]);
                    $_SESSION['app_2'][$SettingName[$i]] = $_POST[$SettingName[$i]];
                }
                Success("Settings has been updated ","100%");
            }
            else Alert("This request is disabled into demo mode.","100%");
            
        }

        public function EditDesign(){
            if($this->settings['demo'] == false ){
                $SettingName = array("Design","Background","favicon","theme","logo_active","logo");
                for($i=0;$i<count($SettingName);$i++){
                    $this->db->Update("setting",array("settingvalue"),array($_POST[$SettingName[$i]]),"settingName",$SettingName[$i]);
                    $_SESSION['app_2'][$SettingName[$i]] = $_POST[$SettingName[$i]];
                }
                Success("Settings has been updated","100%");
            }
            else Alert("This request is disabled into demo mode.","100%");
        }

        public function EditCaptcha(){
            if($this->settings['demo'] == false ){
                $SettingName = array("Captcha","CaptchaSiteKey","CaptchaSecretKey");
                for($i=0;$i<count($SettingName);$i++){
                    $this->db->Update("setting",array("settingvalue"),array($_POST[$SettingName[$i]]),"settingName",$SettingName[$i]);
                    $_SESSION['app_2'][$SettingName[$i]] = $_POST[$SettingName[$i]];
                }
                Success("Settings has been updated","100%");
            }
            else Alert("This request is disabled into demo mode.","100%");
        }

        public function EditUpgrade(){
            if($this->settings['demo'] == false ){
                $SettingName = array("paypal","month_plus","year_plus","month_pro","year_pro");
                for($i=0;$i<count($SettingName);$i++){
                    $this->db->Update("setting",array("settingvalue"),array($_POST[$SettingName[$i]]),"settingName",$SettingName[$i]);
                    $_SESSION['app_2'][$SettingName[$i]] = $_POST[$SettingName[$i]];
                }
                Success("Settings has been updated","100%");
            }
            else Alert("This request is disabled into demo mode.","100%");
        }

        public function EditSocialMedia(){
            if($this->settings['demo'] == false ){
                $SettingName = array("Facebook","Youtube","Twitter","GooglePlus");
                for($i=0;$i<count($SettingName);$i++){
                    $this->db->Update("setting",array("settingvalue"),array($_POST[$SettingName[$i]]),"settingName",$SettingName[$i]);
                    $_SESSION['app_2'][$SettingName[$i]] = $_POST[$SettingName[$i]];
                }
                Success("Settings has been updated","100%");
            }
            else Alert("This request is disabled into demo mode.","100%");
        }

        //Admin Notification
        public function showNotic_admin($admin){
            $result = $this->db->Query("SELECT * FROM admin_notification WHERE status='0' ORDER BY id DESC");
            while($data = mysqli_fetch_array($result)){
                $id = $data['id'];
                echo '<li><a class="app-notification__item" href="#" onclick="show('.$id.')"><span class="app-notification__icon">
                <span class="fa-stack fa-lg"><i class="fa fa-circle fa-stack-2x text-'.$data['color'].'"></i>
                <i class="fa '.$data['icon'].' fa-stack-1x fa-inverse"></i></span></span>';
                echo '<div><p class="app-notification__message">'.$data['title'].'</p>';
                echo '<p class="app-notification__meta">'.get_time_ago($data['date']).'</p>';
                echo '</div></a></li>';
            

            }
        }

        public function countNotic_admin($admin){
            $result = $this->db->Query("SELECT * FROM admin_notification WHERE status='0' ORDER BY id DESC");
            return mysqli_num_rows($result);
        }

        public function showAllNotic_admin($admin){
            $result = $this->db->Query("SELECT * FROM admin_notification ORDER BY id DESC");
            $cpt=0;
            while($data = mysqli_fetch_array($result)){
                echo '<div class="timeline-post"><div class="post-media"><a href="#">';
                echo '<div class="content">';
                echo '<h5><a href="#">'.$data['subject'].'</a></h5>';
                echo '<p class="text-muted"><small>'.$data['date'].'</small></p></div></div>';
                echo '<div class="post-content"><p>'.$data['message'].'</p></div></div>';
                $cpt++;
                if($cpt==50) break;
            }
        }

        public function activeNotice_admin($admin_notice){
            $this->db->Update("admin_notification",array("status"),array("1"),"id",$admin_notice);
        }

        //Pages Privacy Policy - Terms of use
        public function ShowPages($title){
            //title = privacy_policy / terms_of_use
            $result = $this->db->Query("SELECT * FROM pages where title='$title'");
            while($data = mysqli_fetch_array($result)){
                echo $data['content'];
            }
        }

        public function UpdatePages($title,$content){
            //title = privacy_policy / terms_of_use / dmca /
            //$content = mysql_real_escape_string($content);
            $this->db->Update("pages",array("content"),array($content),"title",$title);
            if($title == "privacy_policy")
                Success("Privacy Policy has been updated","100%");
            elseif($title == "terms_of_use")
                Success("Terms of use has been updated","100%");
            elseif($title == "dmca")
                Success("DMCA of use has been updated","100%");
            elseif($title == "copyright")
                Success("Copyright Policy of use has been updated","100%");

        }

        //Manage Plans
        public function Plans($plan){
            $req = $this->db->Query("SELECT * FROM membership_plan WHERE id='$plan'");
            return mysqli_fetch_array($req);
        }

        public function UpdatePlans($plan){
            session_start();
            
            if($plan == "1")
            $val = array(0,0,$_POST['max_size_f'],$_POST['cpm_f'],$_POST['delete_files_f'],$_POST['remove_ads_f'],$_POST['download_delay_f'],$_POST['captcha_f']);

            if($plan == "2")
            $val = array($_POST['month_p'],$_POST['year_p'],$_POST['max_size_p'],$_POST['cpm_p'],$_POST['delete_files_p'],$_POST['remove_ads_p'],$_POST['download_delay_p'],$_POST['captcha_p']);

            if($plan == "3")
            $val = array($_POST['month_pr'],$_POST['year_pr'],$_POST['max_size_pr'],$_POST['cpm_pr'],$_POST['delete_files_pr'],$_POST['remove_ads_pr'],$_POST['download_delay_pr'],$_POST['captcha_pr']);

            $col = array("month","year","max_size","cpm","delete_files","remove_ads","download_delay","captcha");
            $this->db->Update("membership_plan",$col,$val,"id",$plan);

            $plan -=1;
            $_SESSION['app_2']['plans'][$plan]["month"] = $val[0];
            $_SESSION['app_2']['plans'][$plan]["year"] = $val[1];
            $_SESSION['app_2']['plans'][$plan]["max_size"] = $val[2];
            $_SESSION['app_2']['plans'][$plan]["cpm"] = $val[3];
            $_SESSION['app_2']['plans'][$plan]["delete_files"] = $val[4];
            $_SESSION['app_2']['plans'][$plan]["remove_ads"] = $val[5];
            $_SESSION['app_2']['plans'][$plan]["download_delay"] = $val[6];
            $_SESSION['app_2']['plans'][$plan]["captcha"] = $val[7];


            Success("Plan has been updated","100%");
        }

        // Transactions
        public function Transactions(){
            $result = $this->db->Query("SELECT * FROM transaction_plan");
            while($data = mysqli_fetch_array($result))  
            {  
                echo "<tr>";
                echo "<td style='width:5%'>".$data["id"]."</td>";
                echo "<td style='width:20%'>".$data["custom"]."</td>";
                echo "<td style='width:10%'>".$data["payments_date"]."</td>";
                echo "<td style='width:10%'>".$this->settings['currency'].$data["amount"]."</td>";
                echo "<td style='width:15%'>".$data["item_name"]."</td>";
                echo "<td style='width:15%'>".$data["txn_id"]."</td>";
                echo "<td style='width:15%'>".$data["payer_email"]."</td>";
                echo "<td style='width:10%'>".$data["payments_status"]."</td>";
            
                echo "</td></tr>";

            }
        }


       
        



    }
?>