<?php
session_start();
include "../db.php";

include("getway-config.php");

require("razorpay-php/Razorpay.php");

use Razorpay\Api\Api;
use Razorpay\Api\Errors\SignatureVerificationError;

date_default_timezone_set('Asia/Kolkata');
$currentTime = date('Y-m-d g:i a');

if (!isset($_SESSION['uid']) || !isset($_SESSION['uref']) || !isset($_SESSION['utype'])) {
    header("Location: logout.php");
    exit;
}

$success = true;
$error = "Payment Failed";

if (!empty($_POST['razorpay_payment_id'])) {
    $api = new Api($keyId, $keySecret);

    try {
        // Verify the payment signature
        $attributes = array(
            'razorpay_order_id' => $_SESSION['razorpay_order_id'],
            'razorpay_payment_id' => $_POST['razorpay_payment_id'],
            'razorpay_signature' => $_POST['razorpay_signature']
        );

        $api->utility->verifyPaymentSignature($attributes);
    } catch (SignatureVerificationError $e) {
        $success = false;
        $error = 'Razorpay Error : ' . $e->getMessage();
    }
}

if ($success === true) {
    $amount = $_SESSION["amount"];
    $description = $_SESSION["description"];

    date_default_timezone_set('Asia/Kolkata');
    $client_id = $_SESSION["client_id"];
    $product_id = $_SESSION["product_id"];
    $service_name = $_SESSION["service_name"];

    $rechargeBy = $_SESSION["rechargeBy"];
    $fran_id = $_SESSION["fran_id"];
    $rByType = $_SESSION["rByType"];
    $recycle = $_SESSION["recycle"];
    $uniqueCode = $_SESSION["uniqueCode"];

    $client_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '$client_id'");
    if ($client_row = mysqli_fetch_assoc($client_sql)) {
        $client_name = $client_row["uname"];
        $client_contact = $client_row["ucontact"];
        $client_email = $client_row["uemail"];
        $client_address = $client_row["saddress"];
    }

    $sFran_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '$rechargeBy'");
    if ($sFran_row = mysqli_fetch_assoc($sFran_sql)) {
        $sFran_name = $sFran_row["uname"];
    }

    $rpay_order_id = $_SESSION['razorpay_order_id'];
    $rpay_payment_id = $_POST['razorpay_payment_id'];
    $status = "Success";

    // Query to check if the transaction ID exists in the 'payment' table
    $condition1 = "SELECT COUNT(*) AS count FROM payment WHERE p_transectionId = ? AND p_ref = ?";
    $stmt = $con->prepare($condition1);
    $stmt->bind_param('ss', $rpay_payment_id, $uniqueCode);
    $stmt->execute();
    $result = $stmt->get_result();
    $count = $result ? $result->fetch_assoc()['count'] : 0;

    // Query to check if the transaction ID exists in the 'onlinepayment' table
    $condition2 = "SELECT COUNT(*) AS counto FROM onlinepayment WHERE razorpayPaymentId = ?";
    $stmt2 = $con->prepare($condition2);
    $stmt2->bind_param('s', $rpay_payment_id);
    $stmt2->execute();
    $result2 = $stmt2->get_result();
    $count2 = $result2 ? $result2->fetch_assoc()['counto'] : 0;

    // Insert into the payment table if the transaction is new
    if ($count <= 0) {
        $sql = "INSERT INTO payment (p_ref, p_forProduct, p_client, p_by, p_byType, payment, p_des, p_transectionId, p_transectionStatus, p_createDate, p_recycle, p_franchiee, p_subFranchiee) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $con->prepare($sql);
        $stmt->bind_param('sssssssssssss', $uniqueCode, $product_id, $client_id, $rechargeBy, $rByType, $amount, $description, $rpay_payment_id, $status, $currentTime, $recycle, $fran_id, $rechargeBy);
        $stmt->execute();
    }

    // Insert into the online payment table if the payment is new
    if ($count2 <= 0) {
        $sql_onlinepayment = "INSERT INTO onlinepayment (name, phone, service, wRefCode, toValue, razorpayOrderId, razorpayPaymentId, paymentStatus, updatestamp) 
                              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt_onlinepayment = $con->prepare($sql_onlinepayment);
        $stmt_onlinepayment->bind_param('sssssssss', $client_name, $client_contact, $product_id, $uniqueCode, $amount, $rpay_order_id, $rpay_payment_id, $status, $currentTime);
        $stmt_onlinepayment->execute();
    }
    unset($_SESSION["client_id"]);
    unset($_SESSION["product_id"]);
    unset($_SESSION["amount"]);
    unset($_SESSION["description"]);
    unset($_SESSION["uniqueCode"]);
    
    $html = "<script>alert('Payment Done successfully!'); window.location.href = 'view-pay.php?product_id=$product_id';</script>";
} else {
    $html = "<p>Your payment failed. Please try again.</p><p>{$error}</p>";
}

echo $html;
?>