<?php

ob_start();
include('includes/config.php');
require("includes/dbconnect.php");
include('includes/function.php');

$maindb = "slonlmain";
$trandb = "slonltran";
$accdb = "actran";
$stkdb = 'transacn';
$keyfld = "vouchno";

$gid = "id";
$year = mysqli_query($conn, "SELECT * FROM $dbname.`compyear` order by `lastdate` DESC LIMIT 0,1") OR die(mysqli_error($conn));
$fyear = mysqli_fetch_array($year);
$myyear = $fyear['finyear'];
$zroot1 = left($dbname, -4);
$zdb = $zroot1 . '1_' . $myyear;
mysqli_select_db($conn, $zdb);
$source = "SLON";
$auth_key = "Basic Y2tfZDJlM2I4M2NmNjczNzU5YmIyODU3MGJjYWU4ZWE1Yzk4MjA0NmYyNTpjc180MDQwNzMyNDBmMzY4MTM0NGQzNGNjN2I5MjllMTE0NzI0MTZiZGFi";
$username = 'AUTO';

$id = mysqli_query($conn, "SELECT MAX(wpid) AS maxid FROM `$maindb` WHERE wpid !='' LIMIT 0,1 ") or die(mysqli_error($conn));
$fid = mysqli_fetch_assoc($id);
$id1 = ($fid['maxid'] > 0) ? $fid['maxid'] : 16950;

$loop = 0;
while ($loop <= 1000) {
    $curl = curl_init();
    $id1++;
    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://www.loolooherbal.in/wp-json/wc/v2/orders/$id1",
        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_HTTPHEADER => array(
            "Authorization: $auth_key"
        ),
    ));
    $curl_response = curl_exec($curl);
    $mres = json_decode($curl_response, true);

    if ($mres['data']['status'] == 404) {
//        echo "$id1" .", ";
//        die;
        $loop++;
    } else {

        $gstrate_array = ['tax-5' => 5,
            'tax-12' => 12,
            'tax-18' => 18,
            'tax-28' => 28
        ];

        $vouchdt = date('Y-m-d', strtotime($mres['date_created']));
//        browse($vouchdt);
        $gen1 = mysqli_query($conn, "SELECT MAX($keyfld+0) AS maxcode FROM `$maindb` WHERE $keyfld !='' $keycond LIMIT 0,1 ") or die(mysqli_error($conn));
        if (mysqli_num_rows($gen1) > 0) {
            $vvouch = mysqli_fetch_assoc($gen1);
            $qvouch = $vvouch["maxcode"] + 1;
        } else {
            $qvouch = '1';
        }
        $mvouch = $qvouch;
        $mono = date('m', strtotime($mres['date_created']));
        $voucher = $mono . $qvouch;
        $statecode = $mres['billing']['state'];
        if ($statecode == 'TS') {
            $statecode = 'TG';
        }
        if ($statecode == 'DN') {
            $statecode = 'DH';
        }

        $get_party = mysqli_query($conn, "SELECT accode FROM `accmast` WHERE `statealpha` = '$statecode' ")or die(mysqli_error($conn));
        $fparty = mysqli_fetch_assoc($get_party);
        $party = $fparty['accode'];

        $godown = 5;

        $ordno = $mres['number'];

        $paymethod = $mres['payment_method'];

        if ($paymethod == 'cod') {
            $paidby = 'C';
            $purcode = 29;
        } else if ($paymethod == 'razorpay') {
            $paidby = 'Z';
            $purcode = 30;
        } else {
            $paidby = 'P';
            $purcode = 30;
        }

//$paidby = 1;
        $lrno = '';
        $lrdate = '';
        $transporter = '';
        $area = $mres['billing']['city'];
        $staff = '';
        $buyer = '';
        $mcashvouch = '';
        $gstno = '';
        $totdiscamt = 0;
        $roundoff = 0;
        $totbillamt = $mres['total'];
        $postperc;
        $postamt = $mres['shipping_total'];
        $freeflag;
        $freeamount;
        $tottaxable0;
        $pretcs = $totbillamt;
        $tcsperc;
        $tcsamt = 0;
        $wpid;


        if ($mres['billing']['state'] != 'MH') {
            $oms = 1;
        } else {
            $oms = 0;
        }


        $mobile = $mres['billing']['phone'];
        $buyer = $ordno . " " . $mres['billing']['first_name'] . " " . $mres['billing']['last_name'];
        $rem1 = $buyer . " " . $mres['id'];
        $rem2 = '';


        $ctr = 0;
        $i = 0;
        $grossamt = $totdiscamt = $taxableamt = 0;
        $igst1 = $igst5 = $igst12 = $igst18 = $igst28 = $cgst1 = $cgst5 = $cgst12 = $cgst18 = $cgst28 = 0;
        $tottaxble1 = $tottaxble5 = $tottaxble12 = $tottaxble18 = $tottaxble28 = 0;

        mysqli_query($conn, "DELETE FROM `$trandb` WHERE vouchno='$mvouch' ") or die(mysqli_error($conn));
        mysqli_query($conn, "DELETE FROM `$stkdb` WHERE vouchno='$mvouch'  AND `source`='$source'") or die(mysqli_error($conn));
        foreach ($mres['line_items'] as $tran) {
            $ctr++;
            $mbarcode = $prodcode = $tran['sku'];
            $getproddtl = mysqli_query($conn, "SELECT hsncode, gram, unit,mrp,prodgrp FROM `product` WHERE prodcode='$prodcode'") or die(mysqli_error($conn));
            $fproddtl = mysqli_fetch_assoc($getproddtl);
            $gram = $fproddtl['gram'];
            $unit = $fproddtl['unit'];
            $hsncode = $fproddtl['hsncode'];
            $mrp = $fproddtl['mrp'];
            $itemgrp = $fproddtl['prodgrp'];

//    $batch = $fproddtl['batch'];
            $batch = '1';

            $qty = $tran['quantity'];
            $rate = $tran['subtotal'] / $qty;
            $amt = $tran['subtotal'];
            $discperc = 0;
            $discamt = $tran['subtotal'] - $tran['total'];
            $gstname = $tran['tax_class'];
            $gstperc = $gstrate_array[$gstname];
            $cgstrate = $sgstrate = $igstrate = 0;
            $subtot = $amt - $discamt;

            if ($oms == 1) {
                $igstrate = $gstperc;
                $igstamt = $tran['total_tax'];

                if ($igstrate == 0.1) {
                    $igst1 += $igstamt;
                    $tottaxble1 += $subtot;
                } else if ($igstrate == 5) {
                    $igst5 += $igstamt;
                    $tottaxble5 += $subtot;
                } else if ($igstrate == 12) {
                    $igst12 += $igstamt;
                    $tottaxble12 += $subtot;
                } else if ($igstrate == 18) {
                    $igst18 += $igstamt;
                    $tottaxble18 += $subtot;
                } else if ($igstrate == 28) {
                    $igst28 += $igstamt;
                    $tottaxble28 += $subtot;
                }
            } else {
                $cgstrate = $gstperc / 2;
                $cgstamt = $tran['subtotal_tax'] / 2;

                if ($cgstrate == 0.1) {
                    $cgst1 += $cgstamt;
                    $tottaxble1 += $subtot;
                } else if ($gstperc == 5) {
                    $cgst5 += $cgstamt;
                    $tottaxble5 += $subtot;
                } else if ($gstperc == 12) {
                    $cgst12 += $cgstamt;
                    $tottaxble12 += $subtot;
                } else if ($gstperc == 18) {
                    $cgst18 += $cgstamt;
                    $tottaxble18 += $subtot;
                } else if ($gstperc == 28) {
                    $cgst28 += $cgstamt;
                    $tottaxble28 += $subtot;
                }
            }
            $total = $subtot + $cgstamt + $cgstamt + $igstamt;


            $grossamt += $amt;
            $totdiscamt += $discamt;
            $taxableamt += $subtot;

            $totgst1 = $igst1 + $cgst1 + $cgst1;
            $totgst5 = $igst5 + $cgst5 + $cgst5;
            $totgst12 = $igst12 + $cgst12 + $cgst12;
            $totgst18 = $igst18 + $cgst18 + $cgst18;
            $totgst28 = $igst28 + $cgst28 + $cgst28;
            $deemexp = $totgst1;

            mysqli_query($conn, "INSERT INTO `$trandb`(`srno`,vouchno, vouchdt, itemcode, `barcode`, `gram`, hsncode, mrp,
                                                   unit, batch, qty, rate, amount, `discperc`, `discamt`, `cgstrate` , `cgstamt`, `sgstrate`,
                                                   `sgstamt`, `igstrate`, `igstamt`,`total`, `subtot`, `gstperc` )
                                    VALUES('$ctr', '$mvouch', '$vouchdt', '$mbarcode', '$mbarcode', '$gram', '$hsncode','$mrp',
                                           '$unit', '$batch', '$qty', '$rate', '$amt', '$discperc', '$discamt', '$cgstrate', '$cgstamt', '$cgstrate',
                                          '$cgstamt', '$igstrate', '$igstamt', '$total', '$subtot', '$gstperc')") or die(mysqli_error($conn));


//            $gitemgrp = mysqli_query($conn, "SELECT `barcode`,`prodgrp` FROM `product` WHERE `barcode`= '$mbarcode'") or die(mysqli_error($conn));
//            $fitemgrp = mysqli_fetch_array($gitemgrp);
            $group = $source . $mvouch;

            $mqty = $qty * -1;
            mysqli_query($conn, "INSERT INTO `$stkdb`(`srno`, `yearno`, `godown`, `series`,`vouchno`, `vouchdt`,
                                                  `itemcode`, `barcode`, `gram`, `unit`, `qty`, `source`, 
                                                  `batch`, amount, accode, `group` , `rate`, `mrp`, `itemgrp`,
                                                  `ordno`, `monno`, `netamt`)
                                           VALUES('$cnt', '$myyear', '$godown', '$source','$mvouch', '$vouchdt', 
                                                  '$mbarcode', '$mbarcode', '$gram', '$unit', '$mqty', '$source',
                                                  '$batch', '$amt', '$party', '$group', '$rate', '$mrp', '$itemgrp',
                                                  '5', '$mono', $total)") or die(mysqli_error($conn));

            $i++;
        }
        $taxableamt += $postamt;

        mysqli_query($conn, "DELETE FROM `$accdb` WHERE `vouchno`='$mvouch' AND `source`='$source' ") OR die(mysqli_error($conn));
        if ($totbillamt > 0) {
            $minus_amt = ($totbillamt * -1);

            $gstamount = $totgst1 + $totgst5 + $totgst12 + $totgst18 + $totgst28;

            // sale part
            mysqli_query($conn, "INSERT INTO `$accdb`(date, vouchno,`godown`, source, trnno, accode, grpcode, amount, monno)
                            VALUES ('$vouchdt','$mvouch','$godown', '$source', '001', '$purcode','005', '$taxableamt','$mono')") or die(mysqli_error($conn));

//            gst part
            mysqli_query($conn, "INSERT INTO `$accdb`(date, vouchno,`godown`, source, trnno, accode, grpcode, amount, monno)
                            VALUES ('$vouchdt','$mvouch','$godown', '$source', '003', '5','020', '$gstamount','$mono')") or die(mysqli_error($conn));
//            tcs part
            mysqli_query($conn, "INSERT INTO `$accdb`(date, vouchno,`godown`, source, trnno, accode, grpcode, amount, monno)
                            VALUES ('$vouchdt','$mvouch','$godown', '$source', '005', '32','020', '$tcsamt','$mono')") or die(mysqli_error($conn));

//            round off part
            mysqli_query($conn, "INSERT INTO `$accdb`(date, vouchno,`godown`, source, trnno, accode, grpcode, amount, monno)
                            VALUES ('$vouchdt','$mvouch','$godown', '$source', '004', '25','012', '$roundoff','$mono')") or die(mysqli_error($conn));

            // party part
            mysqli_query($conn, "INSERT INTO `$accdb`(date, vouchno, `godown`, source, trnno, accode, grpcode, amount, monno)
                                VALUES ('$vouchdt','$mvouch','$godown', '$source', '002', '$party','010', '$minus_amt','$mono')") or die(mysqli_error($conn));
        }


        mysqli_query($conn, "INSERT INTO `$maindb`(`username`, vouchno, `vouchdt`, `voucher`, `invno`, `monno`, `party`, `mobile`, `oms`, `paidby`, `lrno`, `lrdate`,
                                               `transporter`, `area`, `staff`, `buyer`, `rem1`, `rem2`,  `cashvouch`, `gstno`, `discamt`,`grossamt`, `godown`,roundoff,
                                               `taxableamt`,`cgst1`,`sgst1`,`igst1`,`cgst5`,`sgst5`,`igst5`,`cgst12`,`sgst12`,`igst12`,`cgst18`,`sgst18`,
                                               `igst18`,`cgst28`,`sgst28`,`igst28`,`totgst1`,`totgst5`,`totgst12`,`totgst18`,`totgst28`, `purcode`,`billamt`,
                                               `postperc`,`postamt`,`freeflag`,`freeamount`,`deemexp`,`tottaxble5`, `tottaxble12`, `tottaxble18`,`tottaxble28`,`tottaxable0`,
                                               `pretcs`, `tcsperc`, tcsamt, wpid)
                                      VALUES('$username', '$mvouch', '$vouchdt', '$voucher', '$mvouch', '$mono', '$party', '$mobile', '$oms', '$paidby','$lrno', '$lrdate',
                                             '$transporter', '$area', '$staff','$buyer','$rem1', '$rem2', '$mcashvouch', '$gstno', '$totdiscamt','$grossamt', '$godown','$roundoff',
                                             '$taxableamt','$cgst1','$sgst1','$igst1','$cgst5','$sgst5','$igst5', '$cgst12','$sgst12','$igst12', '$cgst18', '$sgst18',
                                             '$igst18','$cgst28','$sgst28','$igst28','$totgst1','$totgst5','$totgst12','$totgst18','$totgst28', '$purcode','$totbillamt',
                                             '$postperc','$postamt','$freeflag','$freeamount','$deemexp', '$tottaxble5', '$tottaxble12', '$tottaxble18', '$tottaxble28','$tottaxable0',
                                             '$pretcs', '$tcsperc', '$tcsamt', '$id1')") or die(mysqli_error($conn));

//combined sale > 2lac, pan is empty
        curl_close($curl);
        $loop++;
    }
}
?>