<?php

//send sms

try{

    date_default_timezone_set('Asia/Tehran');
    ini_set("log_errors", 1);
    ini_set("error_log", "./z_php_error.log");

    set_exception_handler(function($e) {
        error_log(
            date('Y-m-d H:i:s').' | '.$_SERVER['REQUEST_URI'].' | '.$e->getMessage().PHP_EOL,
            3,
            "./z_sql_error.log"
        );
    });

    header( "Content-type: application/json" );

    //Get required configs:
    require('../../majoris_config.php');
    require('../../majoris_core_config.php');

    foreach ( glob("../v3/class/*.php" ) as $filename )  include $filename;
    db::init();

    if(!isset($_POST['app_id']) || !isset($_POST['phone']) || !isset($_POST['values']) || !isset($_POST['pattern']) ){
        http_response_code(400);
        echo "[app_id] or [phone] or [values] or [pattern] parameters has not sent";
        exit;
    }
    $app_id  = $_POST['app_id'];
    $phone   = trim($_POST['phone']);
    $values  = json_decode($_POST['values'],true);
    $pattern = trim($_POST['pattern']);

    $providersRow = db::fetch( "SELECT * FROM `serverconfig` WHERE `type` = ? AND app_id = ?",['sms_providers', $app_id ]);
    $providers = trim($providersRow['data']);
    if($providers == "") $providers = "[]";
    $providers = json_decode($providers,true);
    $selected_provider_index = -1;
    $index = 0;
    foreach($providers as $item){
        if($item['active']==1)
            $selected_provider_index = $index;
        $index++;
    }
    if($selected_provider_index < 0){
        http_response_code(400);
        echo "sms provider not selected";
        exit;
    }
    $selected_provider = $providers[$selected_provider_index];

    // if(empty($selected_provider['api_url_address'])){
    //     http_response_code(400);
    //     echo "sms server api address is empty";
    //     exit;
    // }

    $sms_company      = trim($selected_provider['code']);
    $sms_servernumber = trim($selected_provider['line_number']);
    $sms_patternid    = trim($pattern);
    $sms_apikey       = trim($selected_provider['api_key_or_token']);
    $sms_secretkey    = trim($selected_provider['api_secret_key']);
    $sms_username     = trim($selected_provider['username']);
    $sms_password     = $selected_provider['password'];
    $sms_rest_api_url = $selected_provider['api_url_address'];


    switch ($sms_company) {

        case 'farazsms':

            //newest api doc 2025: https://github.com/ippanelcom/Edge-Document
            $sms_rest_api_url = "https://edge.ippanel.com/v1/api/send";

            $data = array(
                'sending_type' => "pattern",
                'code'         => $sms_patternid,
                'from_number'  => $sms_servernumber,
                'recipients'   => [$phone],
                'params'       => $values
            );

            $result = CallAPI_farazsms2($sms_rest_api_url,json_encode($data),$sms_apikey);
            
            $ret = json_decode($result,true);

            if(isset($ret['meta']['status']) && $ret['meta']['status'] === true){
                http_response_code(200);
                echo "ok";
                exit;
            }else{
                http_response_code(501);
                $errorMessage = "";
                if(isset($ret['meta']['message'])){
                    $errorMessage = $ret['meta']['message'];
                }else{
                    $errorMessage = $result;
                }
                echo "Error: ".$errorMessage;
                exit;
            }


            // if (strpos($sms_rest_api_url,"api2.ippanel.com") !== false) {
            //     //v2 api of ippanel

            //     $data = array(
            //         'code'      => $sms_patternid,
            //         'sender'    => $sms_servernumber,
            //         'recipient' => $phone,
            //         'variable'  => $values
            //     );
    
            //     $result = CallAPI_farazsms2($sms_rest_api_url,json_encode($data),$sms_apikey);

            //     $ret = json_decode($result,true);
            //     if($ret['status'] == "OK"){
            //         http_response_code(200);
            //         echo "ok";
            //         exit;
            //     }else{
            //         http_response_code(501);
            //         echo "error ".json_encode($result,JSON_UNESCAPED_UNICODE);
            //         exit;
            //     }

            // }else{ // old v1 ippanel

            //     $data = array(
            //         'pattern_code' => $sms_patternid,
            //         'originator'   => $sms_servernumber,
            //         'recipient'    => $phone,
            //         'values'       => $values
            //     );
    
            //     $result = CallAPI_farazsms("POST",$sms_rest_api_url,json_encode($data),$sms_apikey);
            //     //error_log("farazsms json: ".$ret);
            //     $ret = json_decode($result,true);
            //     if($ret['status'] == "OK"){
            //         http_response_code(200);
            //         echo "ok";
            //         exit;
            //     }else{
            //         http_response_code(501);
            //         echo "error ".json_encode($result,JSON_UNESCAPED_UNICODE);
            //         exit;
            //     }

            // }

            break;

        case 'smsdotir':

            $sms_rest_api_url = "https://api.sms.ir/v1/send/verify";
        
            $parameters = [];
            foreach($values as $key => $val){
                $parameters[] = ['name' => $key,'value' => $val];
            }

            $data = array(
                'templateId' => $sms_patternid,
                'mobile'     => $phone,
                'parameters' => $parameters
            );

            $ret = CallAPI_smsdotir($sms_rest_api_url,json_encode($data),$sms_secretkey);
            //error_log("smsdot json: ".$ret);
            $ret = json_decode($ret,true);

            if($ret['status'] == 1){
                http_response_code(200);
                echo "ok";
                exit;
            }else{
                $detail = "";
                if(array_key_exists("title", $ret)){
                    $detail = $ret['title'];
                } else {
                    $detail = json_encode($ret,JSON_UNESCAPED_UNICODE);
                }
                http_response_code(501);
                echo "error : ".$detail;
                exit;
            }

            break;

        default:

            http_response_code(500);
            echo "this provider is not defined: ". $sms_company;
            exit;
            break;

    }

} catch (\Throwable $th) {

    http_response_code(500);
    echo $th->getMessage();
    exit;

}


// Method: POST, PUT, GET etc
// Data: array("param" => "value") ==> index.php?param=value

function CallAPI_farazsms($method, $url, $data = false , $apikey = false)
{
    $curl = curl_init();

    switch ($method)
    {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_PUT, 1);
            break;
        default:
            if (!is_bool($data))
                $url = sprintf("%s?%s", $url, http_build_query($data));
    }

    // Optional Authentication:
    // curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    // curl_setopt($curl, CURLOPT_USERPWD, "username:password");

    if($apikey){
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Authorization: AccessKey '.$apikey
        ));
    }

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);


    $result = curl_exec($curl);

    //error_log("fresult:" . $result);

    if ($result === false) {
        $errorMes = 'majo-fsms: cURL Error: ' . curl_error($curl);
        //error_log("errormes:" . $errorMes);
        return $errorMes;
    }
    curl_close($curl);

    return $result;
    
}

function CallAPI_farazsms2($url, $data, $apikey)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization: '.$apikey
    ));
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec($curl);

    if (curl_errno($curl)) {
        curl_close($curl);
        return 'cURL Error: ' . curl_error($curl);
    }

    curl_close($curl);
    return $result;
    
}

function CallAPI_smsdotir($url, $data = false , $apikey = false)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_POST, 1);

    if ($data)
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

    if($apikey){
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'X-API-KEY: '.$apikey
        ));
    }

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);


    $result = curl_exec($curl);
    curl_close($curl);

    return $result;
    
}
