<?php
include '../backend/db/db.php';
session_start();

date_default_timezone_set('Asia/Colombo');
$date = date('Y-m-d');
$datetime = date('Y-m-d H:i:s');

if (isset($_SESSION['normal_user_bb']) || isset($_SESSION['temp_user_bb'])) {
    if (isset($_SESSION['normal_user_bb'])) {
        $id = htmlspecialchars(strip_tags(trim($_SESSION['normal_user_bb'])), ENT_QUOTES, 'UTF-8');
        $whr = 'User_ID';
        $guest = 0;
    } else if (isset($_SESSION['temp_user_bb'])) {
        $id = htmlspecialchars(strip_tags(trim($_SESSION['temp_user_bb'])), ENT_QUOTES, 'UTF-8');
        $whr = 'temp_id';
        $guest = 1;
    } else {
        $user_id = '';
    }

    $inv_id = htmlspecialchars(strip_tags(trim($_POST['inv_id'])), ENT_QUOTES, 'UTF-8');


    $sql_order = "SELECT * FROM order_details_temp WHERE inv_no = '$inv_id' AND user_id = '$id'";
    $result_order = mysqli_query($conn, $sql_order);
    $row_order = mysqli_fetch_assoc($result_order);


    $g_tot = $row_order['grand_total'];
    $order_id = $row_order['inv_no'];


    $sql_add_order = "INSERT INTO order_details (inv_no, user_id, guest, f_name, l_name, tel_no, email, address_1, address_2, city, district, country, postal_code, special_msg, delivery_type, pay_method, payment_status, order_status, price_total, tot_discount, sub_total, delivery_chg, grand_total, date, order_date) SELECT inv_no, user_id, guest, f_name, l_name, tel_no, email, address_1, address_2, city, district, country, postal_code, special_msg, delivery_type, pay_method, payment_status, order_status, price_total, tot_discount, sub_total, delivery_chg, grand_total, date, now() FROM order_details_temp WHERE inv_no='$order_id' LIMIT 1";
    $result_add_order = mysqli_query($conn, $sql_add_order);

    if ($result_add_order) {
        $sql_del = "DELETE FROM order_details_temp WHERE inv_no = '$inv_id'";
        $result_del = mysqli_query($conn, $sql_del);

        $sql = "INSERT INTO cart_details (user_id, Item, Qty, price, order_id, inv_no, order_date) 
                SELECT User_ID, name, Qty, price, order_id, inv_no, order_date 
                FROM live_cart WHERE inv_no = '$inv_id'";
        $result = mysqli_query($conn, $sql);

        if ($result) {
            $sql2 = "DELETE FROM live_cart WHERE inv_no = '$inv_id'";
            $result2 = mysqli_query($conn, $sql2);
        }

        mysqli_query($conn, "INSERT INTO stock_orders SET ref='$inv_id', date='$date', type='Sales', stock_date='$date'");

        $sqlsq = "SELECT * FROM cart_details WHERE inv_no='$inv_id'";
        $sqls = mysqli_query($conn, $sqlsq);

        while ($rows = mysqli_fetch_array($sqls)) {
            $item = $rows['Item_Code'];
            $qty = $rows['Qty'];
            $id_gr = $rows['id'];
            mysqli_query($conn, "INSERT INTO stock SET stock_card='$item', unit_cost='0', ref='$inv_id', cr_qty='$qty', dr_qty='0', date='$date'");
        }

        $curl = curl_init();
        $inv_id = $row_order['inv_no'];
        $itm_price = (int)$g_tot;
        $fname = $row_order['f_name'];
        $lname = $row_order['l_name'];
        $phone = $row_order['phone'];
        $email = $row_order['email'];
        $ref = str_replace(' ', '', 'sudila-inv'.$inv_id);

        $app_id = "D9OB118E51150014C5B69";
        $app_token = "73b753dcee9d6e0d371a17bcb5a69fc44bd042603a5f446162ce9f3e7d0b13e6f8031490280631b2.LQZD118C3ACF877325A99";
        $hash_salt = '99YN118E51150014C5B90';

        $req = json_encode([
            'amount' => $itm_price,
            'app_id' => $app_id,
            'reference' => $ref,
            'customer_first_name' => $fname,
            'customer_last_name' => $lname,
            'customer_phone_number' => '+94'.str_replace('0', '', $phone),
            'customer_email' => $email,
            'transaction_redirect_url' => 'https://sudila.esrilanka.org/order-completed.php'
        ]);

        $hashed = hash('sha256', $req . $hash_salt);

        curl_setopt_array($curl, [
            CURLOPT_URL => 'https://merchant-api-live-v2.onepay.lk/api/ipg/gateway/request-transaction/?hash=' . $hashed,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_POSTFIELDS => $req,
            CURLOPT_HTTPHEADER => [
                'Authorization: ' . $app_token,
                'Content-Type: application/json'
            ],
        ]);

        $res = curl_exec($curl);
        curl_close($curl);
        $arr = json_decode($res, true);

        $status = $arr["status"];
        $message =  $arr["message"];
        $trans_id = $arr["data"]['ipg_transaction_id'];
        $pay_amt = $arr["data"]['amount']['net_amount'];
        $gateway_url = $arr["data"]['gateway']['redirect_url'];

        $sql2 = "UPDATE order_details SET status='$status', trans_id='$trans_id', pay_amt='$pay_amt' WHERE inv_no='$inv_id'";
        mysqli_query($conn, $sql2);

        $response['status'] = $status;
        $response['gateway_url'] = $gateway_url;

        echo json_encode($response);

        if (isset($_SESSION['temp_user'])) {
            unset($_SESSION['temp_user']);
            unset($_SESSION['gest_user']);
        }

        if (isset($_SESSION['normal_user'])) {
            $sql4 = "UPDATE details_of_users SET order_id = order_id+1 WHERE id = '$id'";
            $result4 = mysqli_query($conn, $sql4);
        }
    } else {
        echo "<script type=\"text/javascript\">";
        echo "window.location.href = 'checkout2'";
        echo "</script>";
    }
} else {
    echo "<script type=\"text/javascript\">";
    echo "window.location.href = 'checkout2'";
    echo "</script>";
}
?>
