<?php
include '../../config.php';
define('API_KEY',$API_KC);
$peyment = mysqli_fetch_assoc(mysqli_query($connect,"SELECT * FROM peyment LIMIT 1"));
$merichentzarin = $peyment['merichentzarin'];
//----------------------------------------------
function factweb($method,$datas=[]){
    $url = "https://api.telegram.org/bot".API_KEY."/".$method;
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$datas);
    $res = curl_exec($ch);
    if(curl_error($ch)){
        var_dump(curl_error($ch));
    }else{ 
        return json_decode($res);
    }
} 
// ------- Get -------
$Authority = $_GET['Authority'];
$user = $_GET['id'];
$amount2 = $_GET['amount'];
$data = array("merchant_id" => "$merichentzarin", "authority" => $Authority, "amount" => $amount2);
$jsonData = json_encode($data);
$ch = curl_init('https://api.zarinpal.com/pg/v4/payment/verify.json');
curl_setopt($ch, CURLOPT_USERAGENT, 'ZarinPal Rest Api v4');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($jsonData)
));
$amount = $amount2 / 10;
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result, true);
if ($err) {
    echo "cURL Error #:" . $err;
} else {
    if ($result['data']['code'] == 100) {
     // Fetch the subscription details to get days
        $query = "SELECT days FROM subs WHERE price = '$amount' AND typesub = 'user'";
        $sub_result = mysqli_query($connect, $query);
        
        if ($sub_result && mysqli_num_rows($sub_result) > 0) {
            $sub_row = mysqli_fetch_assoc($sub_result);
            $days = $sub_row['days']; // Get the number of days

            $datenoww = date('Y-m-d');
            $new_expiry_date = date('Y-m-d', strtotime('+' . $days . ' days'));

            // Update the user's VIP status
            $sql_new = "UPDATE `user` SET vip='yes', expire='$new_expiry_date' WHERE id=$user";    
            mysqli_query($connect, $sql_new);
        }

        factweb('sendMessage',[
            'chat_id' => $user,
            'text' => "✅ پرداخت شما با موفقیت انجام و اشتراک فعال شد",
            'parse_mode' => "HTML",
            'reply_markup' => json_encode([
                'inline_keyboard' => [
                    [
                        ['text' => " 💳 مبلغ پرداختی", 'callback_data' => "none"],
                        ['text' => "$amount تومان", 'callback_data' => "none"]
                    ],
                ]
            ])
        ]);

        // Notify admins
        factweb('sendMessage', [
            'chat_id' => $admins[0],
            'text' => "✅ پرداخت جدید در ربات انجام شد",
            'parse_mode' => "HTML",
            'reply_markup' => json_encode([
                'inline_keyboard' => [
                    [
                        ['text' => "💳 مبلغ پرداختی", 'callback_data' => "none"],
                        ['text' => "$amount تومان", 'callback_data' => "none"]
                    ],
                    [
                        ['text' => "👤 شناسه کاربر", 'callback_data' => "none"],
                        ['text' => "$user", 'url' => "tg://openmessage?user_id=$user"]
                    ]
                ]
            ])
        ]);

        // Success HTML response
        echo '
        <!DOCTYPE html>
        <html lang="fa">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>پرداخت موفق</title>
            <style>
                body {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    height: 100vh;
                    background-color: #f4f4f4;
                    font-family: Arial, sans-serif;
                }
                .message {
                    text-align: center;
                    background-color: #ffffff;
                    padding: 20px;
                    border-radius: 10px;
                    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                }
                .success {
                    color: green;
                    font-size: 24px;
                    font-weight: bold;
                }
                .link {
                    display: inline-block;
                    margin-top: 20px;
                    text-decoration: none;
                    color: #007BFF;
                }
            </style>
        </head>
        <body>
            <div class="message">
                <div class="success">پرداخت با موفقیت انجام شد</div>
                <a href="https://t.me/$bottag" class="link">لطفا به ربات مراجعه کنید</a>
            </div>
        </body>
        </html>
        ';
        die();              
    } else {
            factweb('sendMessage',[
                        'chat_id'=>$user,
                        'text'=>"❌ پرداخت شما انجام نشد",
                        'parse_mode'=>"HTML",
                        ]);
    echo 'پرداخت انجام نشد';
die();   
    }
}