<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

include("../serive/samparka.php");

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

date_default_timezone_set('Asia/Kolkata');

// =========================
// TEST MODE
// =========================
if($_SERVER['REQUEST_METHOD'] == 'GET'){

    $_POST['userId'] = 1;
    $_POST['amount'] = 100;

}

// =========================
// START
// =========================
if ($_SERVER['REQUEST_METHOD'] == 'POST' || $_SERVER['REQUEST_METHOD'] == 'GET') {

    // =========================
    // CHECK INPUTS
    // =========================
    if(!isset($_POST['userId']) || !isset($_POST['amount'])){

        echo json_encode([
            "status" => false,
            "msg" => "Missing userId or amount"
        ]);
        exit;

    }

    $userId = mysqli_real_escape_string($conn, $_POST['userId']);
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);

    // =========================
    // CHECK DB CONNECTION
    // =========================
    if(!$conn){

        echo json_encode([
            "status" => false,
            "msg" => "Database Connection Failed"
        ]);
        exit;

    }

    // =========================
    // USER DETAILS
    // =========================
    $userQ = mysqli_query($conn, "SELECT mobile FROM shonu_subjects WHERE id='$userId'");

    if(!$userQ){

        echo json_encode([
            "status" => false,
            "msg" => mysqli_error($conn)
        ]);
        exit;

    }

    $userA = mysqli_fetch_array($userQ);

    if (!$userA) {

        echo json_encode([
            "status" => false,
            "msg" => "Invalid User"
        ]);
        exit;

    }

    $mobile = $userA['mobile'];

    // =========================
    // UNIQUE ORDER ID
    // =========================
    $order_id = 'ORD' . time() . rand(1000,9999);

    // =========================
    // YAYAPAY API
    // =========================
    $postData = [
        "user_token"      => "5c3cdf9a9fc82d3282b42bbc67949e9f",
        "customer_mobile" => $mobile,
        "amount"          => $amount,
        "order_id"        => $order_id,
        "redirect_url"    => "https://yourdomain.com/payment-success.php",
        "remark1"         => "Deposit",
        "remark2"         => $userId
    ];

    $ch = curl_init();

    curl_setopt_array($ch, [
        CURLOPT_URL => "https://yayapay.shop/api/create-order",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query($postData),
        CURLOPT_HTTPHEADER => [
            "Content-Type: application/x-www-form-urlencoded"
        ],
        CURLOPT_TIMEOUT => 300,
    ]);

    $response = curl_exec($ch);

    // =========================
    // CURL ERROR
    // =========================
    if(curl_errno($ch)){

        echo json_encode([
            "status" => false,
            "msg" => "CURL ERROR",
            "error" => curl_error($ch)
        ]);
        exit;

    }

    curl_close($ch);

    // =========================
    // RAW RESPONSE
    // =========================
    $result = json_decode($response, true);

    if(!$result){

        echo json_encode([
            "status" => false,
            "msg" => "Invalid API Response",
            "raw_response" => $response
        ]);
        exit;

    }

    // =========================
    // SUCCESS
    // =========================
    if(isset($result['status']) && $result['status'] == true){

        $payment_url = $result['data']['payment_url'];

        $createdate = date("Y-m-d H:i:s");

        $insert = mysqli_query($conn, "
            INSERT INTO thevani
            (
                payid,
                balakedara,
                motta,
                dharavahi,
                mula,
                ullekha,
                duravani,
                ekikrtapavati,
                dinankavannuracisi,
                madari,
                pavatiaidi,
                sthiti
            )
            VALUES
            (
                '11',
                '$userId',
                '$amount',
                '$order_id',
                'YAYAPAY',
                '$order_id',
                '$mobile',
                'YAYAPAY',
                '$createdate',
                '1004',
                '2',
                '0'
            )
        ");

        if(!$insert){

            echo json_encode([
                "status" => false,
                "msg" => "Database Insert Failed",
                "db_error" => mysqli_error($conn)
            ]);
            exit;

        }

        echo json_encode([
            "status" => true,
            "msg" => "Order Created Successfully",
            "payment_url" => $payment_url,
            "order_id" => $order_id,
            "api_response" => $result
        ]);

    } else {

        echo json_encode([
            "status" => false,
            "msg" => isset($result['msg']) ? $result['msg'] : 'API Failed',
            "api_response" => $result
        ]);

    }

} else {

    echo json_encode([
        "status" => false,
        "msg" => "Invalid Request Method"
    ]);

}

?>