<?php
    //Function
    function getErrorCaptcha(){
        echo "<br>";
        AlertCenter("<center> The CAPTCHA was incorrect. Try again </center>","100%");
    }

    function addDownload($alias,$cpm,$eCPM,$ip,$country,$data){
        GLOBAL $settings;
        $file = new Upload();
        if($data[5] == 0){
            if(getChanceRand (rand(1,100),$settings["chance"])){
                $file->addDownload($alias,$data[0],$cpm,$eCPM,$ip,$country,$data[6]);
            }else{  
                $file->addNonDownload($alias,$cpm,$eCPM,$ip,$country);
            }                       
        }
    }

    function applyCaptcha($allow_captcha,$plan_allow_captcha){
        if($allow_captcha == "yes")
            if($plan_allow_captcha == "No") // Yes=>RemoveCaptcha / No=>AllowCaptcha
                return true;
            else 
                return false;
        else
            return false;
    }


    // Collect Data From visitor
    if($_SERVER['SERVER_NAME'] == "localhost"){
        $ip="1.1.1.".rand(1,255);
        $country ="MA";
        $countryCode = "USA";
    }else{
        $ip = Get_ip();
        $country = getCountry($ip);
        $countryCode = getCountryCode($ip);
    }
    
    // Create Object
    $file = new Upload();
    $ads = new ads();

    
    if(!isset($_SESSION['cpt_files'])){$_SESSION['cpt_files']=0;}
    if(!isset($_SESSION['isDownloaded'])){$_SESSION['isDownloaded']=0;}
    if(!isset($_SESSION['fisrt_ads'])){$_SESSION['fisrt_ads']=true;}
    $alias = isset($_GET['p'])?Remove_er_sql($_GET['p']):"00";
    
    if(!isset($_SESSION['cpt_id'])) $_SESSION['cpt_id'] = $alias;
    if($_SESSION['cpt_id'] != $alias){
        $_SESSION['cpt_files'] = 0;
        $_SESSION['cpt_id'] = $alias;
    }

    $data = $file->getDownload($alias,$ip);
    $cpm  = $ads->getCPM_pub("file",$countryCode);
    $cpm *= $settings['plans'][$data[7]]["cpm"];
    $eCPM = ($cpm*1000)/2;
   
    // $data == [username, name, nameFile, download, size, isVisitedByIP ,referral ,Plan ]
    // $data == [    0   ,   1 ,     2   ,    3    ,  4  ,       5       ,   6     ,  7  ]

    if(isset($_POST['submit'])) {
        if(applyCaptcha($settings["Captcha"],$settings['plans'][$data[7]]["captcha"])){
            require('reCaptcha/autoload.php');
            if(isset($_POST['g-recaptcha-response'])) {
                $recaptcha = new \ReCaptcha\ReCaptcha($settings["CaptchaSecretKey"]);
                $resp = $recaptcha->verify($_POST['g-recaptcha-response']);
                if ($resp->isSuccess()) {
                    $_SESSION['cpt_files'] = 2;
                    addDownload($alias,$cpm,$eCPM,$ip,$country,$data);
                }else getErrorCaptcha();
            }else getErrorCaptcha(); 
        }
        else{
            $_SESSION['cpt_files'] = 2;
            addDownload($alias,$cpm,$eCPM,$ip,$country,$data);
        }
        $_SESSION['fisrt_ads'] = true;
    }

    
?>