<?php
include 'backend/db/db.php';

// require("assets/PHPMailer/class.phpmailer.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'])) {
  /////////////////////////////////////// START MAIL /////////////////////////////////////////////////


  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_no'])), 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['g_total'];

 
 $sql_add_order = "INSERT INTO order_details (inv_no, user_id,gift_type,title_recip,f_name,l_name,name,phone,address,city,type,land_mark,date_holder,delivery_type,s_instructions,msg,title_sender,sender_name,sender_email,sender_tp,sender_address,country,s_anonymous,order_status,payment_status,date,g_total,dis_card,oredr_pickup_type) SELECT inv_no, user_id,gift_type,title_recip,f_name,l_name,name,phone,address,city,type,land_mark,date_holder,delivery_type,s_instructions,msg,title_sender,sender_name,sender_email,sender_tp,sender_address,country,s_anonymous,order_status,payment_status,date,g_total,dis_card,oredr_pickup_type FROM order_details_temp WHERE inv_no = '$inv_id'";

  $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_Code, Item, Qty, price, order_id, inv_no, order_date) SELECT User_ID, Item_Code, 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);
    } else {
      $sql_log = "INSERT INTO cart_details_error_log (user_id, Item_Code, Item, Qty, price, order_id, inv_no, order_date) SELECT User_ID, Item_Code, name, Qty, price, order_id, inv_no, order_date FROM live_cart WHERE inv_no = '$inv_id'";
      $result_log = mysqli_query($conn, $sql_log);
    }

    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'");
    }

  } else {
    $sql_add_order_log = "INSERT INTO order_details_error_log (u_id, inv_no, f_name, l_name, c_no, email, address, payment_status, order_date, order_status, delivery_opp ,g_total, dis_card, use_cus_points,payment_type) SELECT u_id, inv_no, f_name, l_name, c_no, email, address, payment_status, order_date, order_status, delivery_opp, g_total, dis_card, use_cus_points,payment_type FROM order_details_temp WHERE inv_no = '$inv_id'";

    $result_add_order_log = mysqli_query($conn, $sql_add_order_log);
  }

  $curl = curl_init();

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

   $req = '{"amount":' . str_replace(' ', '', $itm_price) . ',"app_id":"D9OB118E51150014C5B69","reference":"' . str_replace(' ', '', 'sudila-inv'.$inv_id) . '","customer_first_name":"' . str_replace(' ', '', $fname) . '","customer_last_name":"' . str_replace(' ', '', $lname) . '","customer_phone_number":"+94' . str_replace('0', '', $phone) . '","customer_email":"' . str_replace(' ', '', $email) . '","transaction_redirect_url":"https://sudila.esrilanka.org/order-completed"}';

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

  curl_setopt_array($curl, array(
    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 => '{"amount":' . str_replace(' ', '', $itm_price) . ',"app_id":"D9OB118E51150014C5B69","reference":"' . str_replace(' ', '', 'sudila-inv'.$inv_id) . '","customer_first_name":"' . str_replace(' ', '', $fname) . '","customer_last_name":"' . str_replace(' ', '', $lname) . '","customer_phone_number":"+94' . str_replace('0', '', $phone) . '","customer_email":"' . str_replace(' ', '', $email) . '","transaction_redirect_url":"https://sudila.esrilanka.org/order-completed"}',
    CURLOPT_HTTPHEADER => array(
      'Authorization: a48adeb670c09f55f7885258b85b1d884bb934eed7b42c2c29fbf5e7f1ea641a35bb49d89d278d5c.2M3B1189EB7719283CE85',
      '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'];
  // $status_code =  $arr["status_code"];

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

  $response['status'] = $status;
  $response['gateway_url'] = $gateway_url;
  // $response['status_code'] = $status_code;
  //echo $res;

  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);
  }


  // echo "<script type=\"text/javascript\">";

  // echo "window.location.href = 'order-completed'";

  //echo "</script>";
} else {
  echo "<script type=\"text/javascript\">";

  echo "window.location.href = 'checkout2'";

  echo "</script>";
}
