<?php

namespace App\System\Module;
use App\System\Basic\beRouter;
use App\System\Model\PaymentModel;
use App\System\Model\SettingModel;
use App\System\Model\UserInfoModel;
use App\System\Vendor\Auth;

class vallet {
    public function vallet_info(){
        return [
            "name" => "Vallet",
            "description" => "Vallet ile ödeme almanızı sağlar",
            "version" => "1.2",
            "vercode" => 12,
            "author" => "ITenGriTR",
        ];
    }
    public function vallet_is_activated(){
        $settings = SettingModel::beGetSettings("vallet_status");
        return $settings["vallet_status"] == 1 ? true:false;
    }
    public function vallet_currency(){
        return 1;
    }
    public function vallet_template($params = []){
        $settings = SettingModel::beGetSettings("vallet_methodfee");
        $price = $params["total"];
        $currency = $params["currency"];
        $newprice = $price*(100+$settings["vallet_methodfee"])/100;
        return beGetView("global.vallet",["price" => round($newprice,2),"currency" => $currency]);
    }
    public function vallet_create_payment($invoice){
        $settings = SettingModel::beGetSettings("vallet_merchant_id,vallet_merchant_key,vallet_merchant_secret,vallet_merchant_username,vallet_methodfee");
        $user = Auth::beGetUser();
        $price = $invoice["itotal"];
        $invoice["ifee"] = round($price*$settings["vallet_methodfee"]/100,2);
        $price = $price*(100+$settings["vallet_methodfee"])/100;
        $price = round($price,2);
        $userinfo = UserInfoModel::beSelect("uiphone,uiaddress")->beWhere("uid",$user["uid"])->beGet();
        $post_vals = [
            "userName" => $settings["vallet_merchant_username"],
            "password" => $settings["vallet_merchant_key"],
            "shopCode" => $settings["vallet_merchant_id"],
            "productName" => $invoice["iname"],
            "productData" => [
                "productName" => $invoice["iname"],
                "productPrice" => 50,
                "productType" => "DIJITAL_URUN"
            ],
            "productType" => "DIJITAL_URUN",
            "productsTotalPrice" => $price,
            "orderPrice" => $price,
            "currency" => "TRY",
            "orderId" => $invoice["oid"],
            "locale" => "tr",
            "conversationId" => $invoice["oid"],
            "buyerName" => $user["name"],
            "buyerSurName" => $user["surname"],
            "buyerGsmNo" => $userinfo["uiphone"],
            "buyerIp" => beRouter::$beUserIP,
            "buyerMail" => $user["email"],
            "buyerAdress" => $userinfo["uiaddress"],
            "buyerCountry" => "TR",
            "buyerCity" => "TR",
            "buyerDistrict" => "TR",
            "callbackOkUrl" => beGetRoute("invoice.payment.callback")."?module=vallet",
            "callbackFailUrl" => beGetRoute("invoice.payment.callback")."?module=vallet",
            "module" => "PHP"
        ];
        $hashstring = $post_vals["orderId"].$post_vals["currency"].$post_vals["orderPrice"].$post_vals["productsTotalPrice"].$post_vals["productType"].$post_vals["callbackOkUrl"].$post_vals["callbackFailUrl"];
        $post_vals["hash"] = base64_encode(pack("H*",sha1($settings["vallet_merchant_username"].$settings["vallet_merchant_key"].$settings["vallet_merchant_id"].$hashstring.$settings["vallet_merchant_secret"])));
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,"https://www.vallet.com.tr/api/v1/create-payment-link");
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$post_vals);
        curl_setopt($ch,CURLOPT_REFERER,beGetConfig("domain"));
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        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,
            "payment_page_url" => $result["payment_page_url"]
        ];
        return [
            "status" => true,
            "payment" => $payment,
            "invoice" => $invoice,
            "message" => "Başarılı bir şekilde ödeme işleminiz oluşturuldu!",
            "url" => $result["payment_page_url"]
        ];
    }
    public function vallet_pay_callback(){
        if($_POST["status"] != "success"){
            beError("Ödeme Hatası",$_POST["errorMessage"]);
        }
        beRouter::beRedirect(beGetRoute("client.dashboard"));
    }
    public function vallet_pay_notification(){
        $settings = SettingModel::beGetSettings("vallet_merchant_id,vallet_merchant_secret");
        $hashstring = $_POST["orderId"].$_POST["paymentCurrency"].$_POST["orderPrice"].$_POST["productsTotalPrice"].$_POST["productType"].$settings["vallet_merchant_id"].$settings["vallet_merchant_secret"];
        $hash = base64_encode(pack("H*",sha1($hashstring)));
        if($hash != $_POST["hash"]){
            return ["status" => false,"message" => "Token doğrulamadı lütfen sistemi kontrol edin!"];
        }
        $oid = $_POST["conversationId"];
        $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($_POST["paymentStatus"] != "paymentOk"){
            return ["status" => false,"message" => "OK"];
        }
        PaymentModel::beUpdate(["pstatus" => "1"])->beWhere("pid",$payment["pid"])->beExecute();
        return ["status" => true,"payment" => $payment,"add_accounting" => true,"message" => "OK"];
    }
}
?>