<?php
header("Content-Type: text/html; charset=utf-8");

if(isset($_POST["contract_id"])){
    include "../actions/dbPDO.php"; 
    $contract_id    = $_POST["contract_id"];
    $sanad          = $_POST["sanad"];
    $father         = $_POST["father"];
    $smsKind        = $_POST["smsKind"];
    
    $result = SMSapi::sendSMS($db,$contract_id,$sanad,$father,$smsKind) ;
    echo $result  ;
}



class SMSapi{

    public static function sendSMS($db,$contract_id,$sanad,$father,$smsKind)
    {
        $money = 0 ;
        $data  = array();
    try {
        $get = SMSapi::getdata($db,$contract_id,$sanad,$smsKind);
        $cust_id = $get['cust_id'];
        if(($smsKind == 1)||($smsKind == 5)){
            $money = intval($get['money']);
        }
        $sent = SMSapi::sent($db,$cust_id,$sanad,$smsKind);
        if($sent){
            return        "<div class='alert alert-danger'>
            <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
            <b> تم الارسال لهذا العميل منذ فترة قريبة جدا</b>
            </div> " ;
            }
        $message_text = SMSapi::messageFormat($contract_id,$get['kind'],$get['numbers'],$money,$sanad,$smsKind);
        // return $message_text ;
        $user = 'alwasamrent';
        $password = 'Salem2030';
        $sendername = 'ALWASAMRENT';
        $text = urlencode( $message_text);
        $to = $get['phone'];
        // auth call
        $url = "http://www.4jawaly.net/api/sendsms.php?username=$user&password=$password&numbers=$to&message=$text&sender=$sendername&unicode=E&return=full";
        //������ ������ json
        //$url = "http://www.4jawaly.net/api/sendsms.php?username=$user&password=$password&numbers=$to&message=$text&sender=$sendername&unicode=E&return=json";
        // ������ ������ xml
        //$url = "http://www.4jawaly.net/api/sendsms.php?username=$user&password=$password&numbers=$to&message=$text&sender=$sendername&unicode=E&return=xml";
        // ������ ������ string 
        //$url = "http://www.4jawaly.net/api/sendsms.php?username=$user&password=$password&numbers=$to&message=$text&sender=$sendername&unicode=E";
        // Call API and get return message
        //fopen($url,"r");
        // $handle = fopen($url, 'r');
        // $respond = stream_get_contents($handle);
        $url = str_replace("\n", ' ', $url);
    // $respond = file_get_contents($url);
            // echo nl2br($respond);
    $respond = 'test free' ;
    $respond = strip_tags($respond);
    SMSapi::createHistory($db,$cust_id,$to,$contract_id,$sanad,$smsKind,$message_text,$respond,$father);
         $data["msg"] =  "<div class='alert alert-success'>
            <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
            <b>".$message_text."</b>
            </div>" ;
            // $data["url"] = $url ;
        return  $url ;

    } catch(Exception $e){
        return $e ;
    }
}
    public static function getdata($db,$contract_id,$sanad,$smsKind){
        $data  = array();
        $query = "SELECT customers.cust_id ,customers.phone , customers.idSA , cars.kind , cars.letters , cars.numbers , cars.model From customers , contracts ,cars
                    WHERE customers.cust_id = contracts.cust_id AND contract_id = :contract_id AND contracts.carid = cars.carid" ;
        $query2 = "SELECT customers.cust_id ,customers.phone , customers.idSA , cars.kind , cars.letters , cars.numbers , cars.model From customers , contracts ,cars
        WHERE customers.cust_id = contracts.cust_id2 AND contract_id = :contract_id AND contracts.carid = cars.carid" ;
        $query3 = "SELECT money_in From invoice WHERE in_id =:sanad";
        $query4 = "SELECT money_out From outvoice WHERE out_id=:sanad";

        $stmt = $db->prepare($query);
        $stmt->execute(array(':contract_id'=>$contract_id));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if($row["idSA"]<3000000000){
            $data["cust_id"]    = $row["cust_id"] ;
            $data["phone"]      = $row["phone"] ;
            $data["kind"]       = $row["kind"] ;
            $data["letters"]    = $row["letters"] ;
            $data["numbers"]    = $row["numbers"] ;
            $data["model"]      = $row["model"] ;
        }else{
            $stmt = $db->prepare($query2);
            $stmt->execute(array(':contract_id'=>$contract_id));
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
                $data["cust_id"]    = $row["cust_id"] ;
                $data["phone"]      = $row["phone"] ;
                $data["kind"]       = $row["kind"] ;
                $data["letters"]    = $row["letters"] ;
                $data["numbers"]    = $row["numbers"] ;
                $data["model"]      = $row["model"] ;
         }
         if($smsKind == 1){
        $stmt = $db->prepare($query3);
        $stmt->execute(array(':sanad'=>$sanad));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
            $data["money"]      = $row["money_in"] ;
         }else if ($smsKind == 5){
        $stmt = $db->prepare($query4);
        $stmt->execute(array(':sanad'=>$sanad));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
            $data["money"]      = $row["money_out"] ;
         }

    return $data ;
    }

    public static function sent($db,$cust_id,$sanad,$smsKind){
        $query = "SELECT max(audate) as time1 from smshistory WHERE cust_id = :cust_id" ;
        $stmt = $db->prepare($query);
        $stmt->execute(array(':cust_id'=>$cust_id));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if(!empty($row)){
            $start = strtotime($row['time1']);
            $today = date("Y-m-d H:i:s");
            $end = strtotime($today);
            // $end = $end + 3600 ;
            $mano =   $end -$start  ;
            if($mano < 90){                 
             return true ; 
            }else{
                if(($smsKind == 1)||($smsKind == 5)){
                    $inv =SMSapi::in_outSMS($db,$sanad,$smsKind) ;
                    if(empty($inv)){return false ;}else{return true ;}
                }else{
                    return false ; 
                }
            }               
        }else{   return false ;  }
    }
    public static function messageFormat($contract_id,$kind,$numbers,$money,$sanad,$smsKind){
        switch ($smsKind) {
            case '1':
                $message = " تم قبض مبلغ".$money." ريال سند ".$sanad." عقد ".$contract_id." ".$kind." ".$numbers ;
                break;
            case '2':
                $message = "عميلنا العزيز الرجاء مراجعة الفرع لتجديد عقد ".$contract_id." ".$kind." ".$numbers ;
                break;
            case '3':
                $message = " عميلنا العزيز ميعاد تغير زيت ".$kind." ".$numbers." برجاء تغيير زيت المحرك " ;
                break;
            case '4':
                $message = "برجاء مراجعة الفرع السيارة ".$kind." ".$numbers." بحاجة للصيانة الدورية " ;
                break;
           case '5':
                $message = "تم صرف ".$money." ريال سند ".$sanad." عقد ".$contract_id." ".$kind." ".$numbers ;
                break;
            case '6':
                    $message = "عميلنا العزيز تم تطبيق الأمر الملكي بزيادة ضريبة القيمة المضافةإلي 15%اليوم1 /7";
                    break;
            default:
                $message = "سعدنا بخدمتكم في الوسام المعتمد لتاجير السيارات .. في رعاية الله";
                break;
        }
        return $message ;
    }
    public static function createHistory($db,$cust_id,$phone,$contract_id, $sanad , $smsKind,$message_text,$respond,$father)
    {
    $sql = $db->prepare('INSERT INTO smshistory(cust_id,phone,contract_id, sanad , smsKind, message_text, respond, father)
                                        VALUES(:cust_id,:phone,:contract_id, :sanad ,:smsKind,:message_text,:respond,:father)');
       if($sql->execute(array(':cust_id'=>$cust_id,':phone'=>$phone,':contract_id'=>$contract_id,':sanad'=>$sanad,':smsKind'=>$smsKind,':message_text'=>$message_text,':respond'=>$respond,':father'=>$father))){
                return true;
            }else{ return false ;}
    }
    public static function contractSMS($db,$contract_id){
        // return current contract sent message to customer
        $query = "SELECT * from smshistory WHERE contract_id = :contract_id" ;
        $stmt = $db->prepare($query);
        $stmt->execute(array(':contract_id'=>$contract_id));
        $row = $stmt-> fetchAll();
        return $row ;
    }
    public static function in_outSMS($db,$sanad,$smsKind){
        //return current contract sent sms to customer
        $query = "SELECT * from smshistory WHERE sanad = :sanad AND smsKind =:smsKind" ;
        $stmt = $db->prepare($query);
        $stmt->execute(array(':sanad'=>$sanad,':smsKind'=>$smsKind));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row ;
    }
    
    public static function cust_SMS($db,$cust_id){
        //return current customer sent sms to customer
        $query = "SELECT * from smshistory WHERE cust_id = :cust_id" ;
        $stmt = $db->prepare($query);
        $stmt->execute(array(':cust_id'=>$cust_id));
        $row = $stmt-> fetchAll();
        return $row ;
    }
}
 
?>