<?php

namespace App\System\Module;

use App\System\Basic\beModel;
use App\System\Basic\beRouter;
use App\System\Model\CurrencyModel;
use App\System\Model\PaymentModel;
use App\System\Model\SettingModel;
use App\System\Model\UserInfoModel;
use App\System\Vendor\Auth;

class paytr {
    public function paytr_info(){
        return [
            "name" => "PayTR",
            "description" => "PayTR ile ödeme almanızı sağlar",
            "version" => "1.2",
            "vercode" => 12,
            "author" => "ITenGriTR",
        ];
    }
    public function paytr_is_activated(){
        $settings = SettingModel::beGetSettings("paytr_status");
        return $settings["paytr_status"] == 1 ? true:false;
    }
    public function paytr_currency(){
        return 1;
    }
    public function paytr_template($params = []){
        $settings = SettingModel::beGetSettings("paytr_methodfee,paytr_method");
        $price = $params["total"];
        $currency = $params["currency"];
        $newprice = $price*(100+$settings["paytr_methodfee"])/100;
        return beGetView("global.paytr",["price" => round($newprice,2),"currency" => $currency]);
        switch($settings["paytr_method"]){
            case "iframe" :
                return beGetView("global.paytr.iframe",["price" => round($newprice,2),"currency" => $currency]);
                break;
            case "non3d" :
                return beGetView("global.paytr.non3d",["price" => round($newprice,2),"currency" => $currency]);
                break;
        }
    }
    public function paytr_create_payment($invoice){
        $settings = SettingModel::beGetSettings("paytr_merchant_id,paytr_merchant_key,paytr_merchant_secret,paytr_methodfee,paytr_method");
        $user = Auth::beGetUser();
        $price = $invoice["itotal"];
        $invoice["ifee"] = round($price*$settings["paytr_methodfee"]/100,2);
        $price = $price*(100+$settings["paytr_methodfee"])/100;
        $price = round($price,2);
        $userinfo = UserInfoModel::beSelect("uiphone,uiaddress")->beWhere("uid",$user["uid"])->beGet();
        $merchant = [
            "id" => $settings["paytr_merchant_id"],
            "key" => $settings["paytr_merchant_key"],
            "salt" => $settings["paytr_merchant_secret"],
            "oid" => $invoice["oid"],
            "currency" => "TL"
        ];
        $payment = [
            "amount" => $price,
            "no_installment" => 0,
            "max_installment" => 0,
            "test_mode" => 1
        ];
        $user = [
            "uid" => $user["uid"],
            "email" => $user["email"],
            "ip" => beRouter::$beUserIP,
            "basket" => base64_encode(json_encode([
                $invoice["iname"],
                $invoice["itotal"],
                1
            ],JSON_UNESCAPED_UNICODE)),
            "name" => $user["name"]." ".$user["surname"],
            "adress" => $userinfo["uiaddress"],
            "phone" => $userinfo["uiphone"]
        ];
        if(!$user["adress"]){
            $user["adress"] = "Bilinmeyen adres bilgisi!";
        }
        switch($settings["paytr_method"]){
            case "iframe" :
                $hash_str = $merchant["id"].$user["ip"].$merchant["oid"].$user["email"].$payment["amount"].$user["basket"].$payment["no_installment"].$payment["max_installment"].$merchant["currency"].$payment["test_mode"];
                $token = base64_encode(hash_hmac("sha256",$hash_str.$merchant["salt"],$merchant["key"],true));
                $post_vals = [
                    "merchant_id" => $merchant["id"],
                    "merchant_oid" => $merchant["oid"],
                    "user_ip" => $user["ip"],
                    "email" => $user["email"],
                    "payment_amount" => $payment["amount"],
                    "paytr_token" => $token,
                    "user_basket" => $user["basket"],
                    "debug_on" => 0,
                    "no_installment" => $payment["no_installment"],
                    "max_installment" => $payment["max_installment"],
                    "user_name" => $user["name"],
                    "user_address" => $user["adress"],
                    "user_phone" => $user["phone"],
                    "merchant_ok_url" => beGetRoute("client.dashboard"),
                    "merchant_fail_url" => beGetRoute("client.invoice.invoices.unpaid"),
                    "timeout_limit" => "5",
                    "currency" => $merchant["currency"],
                    "test_mode" => $payment["test_mode"]
                ];	
                $ch = curl_init();
                curl_setopt($ch,CURLOPT_URL,"https://www.paytr.com/odeme/api/get-token");
                curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
                curl_setopt($ch,CURLOPT_POST,1);
                curl_setopt($ch,CURLOPT_POSTFIELDS,$post_vals);
                curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
                curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
                curl_setopt($ch,CURLOPT_IPRESOLVE,CURL_IPRESOLVE_V4);
                curl_setopt($ch,CURLOPT_TIMEOUT,10);
                $result = curl_exec($ch);
                if(curl_errno($ch)){
                    return ["status" => false,"message" => "Bir sorun oluştu: ".curl_error($ch)."(".curl_errno($ch).")"];
                }
                $result = json_decode($result,true);
                if($result["status"] != "success"){
                    return ["status" => false,"message" => "Ödeme oluştururlurken bir şeyler ters gitti".print_r($result,true)];
                }
                curl_close($ch);
                $payment = [
                    "price" => $price,
                    "token" => $result["token"]
                ];
                return [
                    "status" => true,
                    "payment" => $payment,
                    "invoice" => $invoice,
                    "message" => "Başarılı bir şekilde ödeme işleminiz oluşturuldu!",
                    "url" => "https://www.paytr.com/odeme/guvenli/{$result['token']}"
                ];
                break;
            case "non3d" :
                $usertoken = beModel::beTable("be_paytr_user")->beWhere("uid",$user["uid"])->beGet();
                $cardid = $_POST["cardid"];
                $non3d = 0;
                $hash_str = $merchant["id"].$user["ip"].$merchant["oid"].$user["email"].$payment["amount"]."card"."0".$merchant["currency"].$payment["test_mode"].$non3d;
                $token = base64_encode(hash_hmac("sha256",$hash_str.$merchant["salt"],$merchant["key"],true));
                if($cardid){
                    $cardcvv = $_POST["cardcvv"];
                    if(strlen($cardcvv) != 3){
                        return ["status" => false,"message" => "Kart güvenlik numarası(CVV) doğrulanamadı lütfen kontrol edin!"];
                    }
                    $post_vals = [
                        "merchant_id" => $merchant["id"],
                        "merchant_oid" => $merchant["oid"],
                        "user_ip" => $user["ip"],
                        "email" => $user["email"],
                        "payment_amount" => $payment["amount"],
                        "payment_type" => "card",
                        "paytr_token" => $token,
                        "user_basket" => $user["basket"],
                        "installment_count" => "0",
                        "no_installment" => $payment["no_installment"],
                        "max_installment" => $payment["max_installment"],
                        "user_name" => $user["name"],
                        "user_address" => $user["adress"],
                        "user_phone" => $user["phone"],
                        "merchant_ok_url" => beGetRoute("client.dashboard"),
                        "merchant_fail_url" => beGetRoute("client.invoice.invoices.unpaid"),
                        "timeout_limit" => "5",
                        "currency" => $merchant["currency"],
                        "test_mode" => $payment["test_mode"],
                        "debug_on" => $payment["test_mode"],
                        "non_3d" => $non3d,
                        "non3d_test_failed" => 0,
                        "cc_owner" => $user["name"]." ".$user["surname"],
                        "utoken" => $usertoken["icusertoken"],
                        "ctoken" => $cardid,
                        "cvv" => $cardcvv
                    ];
                }
                else{
                    $savecard = (int)$_POST["savecard"] == 1 ? true:false;
                    $cardnumber = preg_replace("/[^0-9]/","",str_replace(" ","",$_POST["cardNumer"]));
                    if(strlen($cardnumber) != 16){
                        return ["status" => false,"message" => "Kart numarası doğrulanamadı lütfen kontrol edin!"];
                    }
                    $cardcvv = preg_replace("/[^0-9]/","",$_POST["cardCvc"]);
                    if(strlen($cardcvv) != 3){
                        return ["status" => false,"message" => "Kart güvenlik numarası(CVV) doğrulanamadı lütfen kontrol edin!"];
                    }
                    $cardvalidate = explode("/",str_replace(" ","",$_POST["cardValidate"]));
                    $expiramm = preg_replace("/[^0-9]/","",$cardvalidate[0]);
                    if((int)$expiramm < 0 || (int)$expiramm > 12){
                        return ["status" => false,"message" => "Kart son kullanım doğrulanamadı lütfen kontrol edin!"];
                    }
                    $expirayy = preg_replace("/[^0-9]/","",$cardvalidate[1]);
                    if((int)$expirayy < 25 || (int)$expirayy > 100){
                        return ["status" => false,"message" => "Kart son kullanım doğrulanamadı lütfen kontrol edin!"];
                    }
                    beModel::beInsert([
                        "uid" => $user["uid"],
                        "iid" => $invoice["iid"],
                        "iccardnumber" => $cardnumber,
                        "iccardexpire" => $expiramm."/20".$expirayy,
                        "icipaddress" => beRouter::$beUserIP,
                        "icdateline" => BE_TIME
                    ],"be_paytr_cards");
                    $post_vals = [
                        "merchant_id" => $merchant["id"],
                        "merchant_oid" => $merchant["oid"],
                        "user_ip" => $user["ip"],
                        "email" => $user["email"],
                        "payment_amount" => $payment["amount"],
                        "payment_type" => "card",
                        "paytr_token" => $token,
                        "user_basket" => $user["basket"],
                        "installment_count" => "0",
                        "no_installment" => $payment["no_installment"],
                        "max_installment" => $payment["max_installment"],
                        "user_name" => $user["name"],
                        "user_address" => $user["adress"],
                        "user_phone" => $user["phone"],
                        "merchant_ok_url" => beGetRoute("client.dashboard"),
                        "merchant_fail_url" => beGetRoute("client.invoice.invoices.unpaid"),
                        "timeout_limit" => "5",
                        "currency" => $merchant["currency"],
                        "test_mode" => $payment["test_mode"],
                        "debug_on" => $payment["test_mode"],
                        "non_3d" => $non3d,
                        "non3d_test_failed" => 0,
                        "cc_owner" => $user["name"]." ".$user["surname"],
                        "card_number" => $cardnumber,
                        "expiry_month" => $expiramm,
                        "expiry_year" => $expirayy,
                        "cvv" => $cardcvv,
                    ];
                    if($savecard){
                        $post_vals["store_card"] = 1;
                    }
                    if($usertoken){
                        $post_vals["utoken"] = $usertoken["icusertoken"];
                    }
                }
                $ch = curl_init();
                curl_setopt($ch,CURLOPT_URL,"https://www.paytr.com/odeme");
                curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
                curl_setopt($ch,CURLOPT_POST,1);
                curl_setopt($ch,CURLOPT_POSTFIELDS,$post_vals);
                curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
                curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
                curl_setopt($ch,CURLOPT_IPRESOLVE,CURL_IPRESOLVE_V4);
                curl_setopt($ch,CURLOPT_TIMEOUT,10);
                $result = curl_exec($ch);
                if(curl_errno($ch)){
                    return ["status" => false,"message" => "Bir sorun oluştu: ".curl_error($ch)."(".curl_errno($ch).")"];
                }
                curl_close($ch);
                return ["status" => true,"message" => "Başarılı bir şekilde ödeme oluşturuldu!","data" => $result];
                break;
        }
    }
    public function paytr_pay_page($invoice){
        $settings = SettingModel::beGetSettings("paytr_merchant_id,paytr_merchant_key,paytr_merchant_secret,paytr_methodfee,paytr_method");
        $user = Auth::beGetUser($invoice["uid"]);
        $currencies = CurrencyModel::beGetCurrencies("cid,cname,cicon");
        $comussion = round($invoice["itotal"]*$settings["iyzico_methodfee"]/100,2);
        $invoice["itotal"] += $comussion;
        switch($settings["paytr_method"]){
            case "non3d" :
                $usertoken = beModel::beTable("be_paytr_user")->beWhere("uid",$user["uid"])->beGet();
                $cards = [];
                if($usertoken){
                    $post_vals = [
                        "merchant_id" => $settings["paytr_merchant_id"],
                        "utoken" => $usertoken["icusertoken"],
                        "paytr_token" => base64_encode(hash_hmac("sha256",$usertoken["icusertoken"].$settings["paytr_merchant_secret"],$settings["paytr_merchant_key"],true))
                    ];
                    $ch=curl_init();
                    curl_setopt($ch,CURLOPT_URL,"https://www.paytr.com/odeme/capi/list");
                    curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch,CURLOPT_POST,1);
                    curl_setopt($ch,CURLOPT_POSTFIELDS,$post_vals);
                    curl_setopt($ch,CURLOPT_FRESH_CONNECT,true);
                    curl_setopt($ch,CURLOPT_TIMEOUT,20);
                    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
                    $result = curl_exec($ch);
                    curl_close($ch);
                    $result = json_decode($result,true);
                    if($result["status"] != "error"){
                        $cards = $result;
                    }
                }
                return ["status" => true,"template" => beGetView("global.paytr.non3d",["invoice" => $invoice,"cards" => $cards,"currencies" => $currencies,"settings" => $settings])];
                break;
            case "iframe" :
                return ["status" => true,"template" => beGetView("global.paytr.iframe",["invoice" => $invoice,"currencies" => $currencies,"settings" => $settings])];
                break;
        }
    }
    public function paytr_pay_notification(){
        $settings = SettingModel::beGetSettings("paytr_merchant_key,paytr_merchant_secret,paytr_method");
        $hash = base64_encode(hash_hmac("sha256",$_POST["merchant_oid"].$settings["paytr_merchant_secret"].$_POST["status"].$_POST["total_amount"],$settings["paytr_merchant_key"],true));
        if($hash != $_POST["hash"]){
            return ["status" => false,"message" => "Token doğrulamadı lütfen sistemi kontrol edin!"];
        }
        $oid = $_POST["merchant_oid"];
        $payment = PaymentModel::beSelect("pid,cid,uid,iid,ptotal,pstatus")->beWhere("pid",$oid)->beGet();
        if(!$payment){
            return ["status" => false,"message" => "OK"];
        }
        if($payment["pstatus"] != 0){
            PaymentModel::beUpdate(["pstatus" => "-1"])->beWhere("pid",$payment["pid"])->beExecute();
            return ["status" => false,"message" => "OK"];
        }
        if($_POST["status"] != "success"){
            PaymentModel::beUpdate(["pstatus" => "-1"])->beWhere("pid",$payment["pid"])->beExecute();
            return ["status" => false,"message" => "OK"];
        }
        if($settings["paytr_method"] == "non3d" && $_POST["utoken"]){
            $usertoken = beModel::beTable("be_paytr_user")->beWhere("uid",$payment["uid"])->beGet();
            if(!$usertoken){
                beModel::beInsert([
                    "uid" => $payment["uid"],
                    "icusertoken" => $_POST["utoken"],
                    "icdateline" => BE_TIME
                ]);
            }
        }
        PaymentModel::beUpdate(["pstatus" => "1"])->beWhere("pid",$payment["pid"])->beExecute();
        return ["status" => true,"payment" => $payment,"add_accounting" => true,"message" => "OK"];
    }
}
?>