<?php

    require_once __DIR__ . '/catchexception.php';
    // include db connect class
    require_once __DIR__ . '/db_config.php';
    // array for JSON response
    $response = array();
    if (!isset($_GET['from']) || !isset($_GET['to']) || !isset($_GET['branchcode'])) {
        $response["success"] = 0;
        $response["message"] = "Required field(s) is missing";

        echo json_encode($response, JSON_UNESCAPED_UNICODE);
        die;
    }


    $fromdate = ($_GET['from']);
    $todate = ($_GET['to']);
    $branchcode = ($_GET['branchcode']);
    date_default_timezone_set('Asia/Kolkata');
    // $branchcode = 171;  // this is for noida 62 branch , but api created wrongly
    // $branchcode = 10;  // this is for noida 62 branch , but api created wrongly


    try{
        if ($fromdate != "" && $todate != "" && $branchcode != "") {
            $paraquery = "SELECT a.voucherno,a.transactiondate,a.createddate,
                                coalesce(CAST((a.basicamount) AS DECIMAL(1000, 2)),0)  as gross_sales_amount,
                                coalesce(CAST((netamount) AS DECIMAL(1000, 2)),0)  as netamount,salestime,
                                coalesce(CAST((discamount) AS DECIMAL(1000, 2)),0) as discount,
                                coalesce(customermobileno,'') as mobilenumber,coalesce(customername,'') as customername,
                                coalesce(cgstamount,0) as cgst,coalesce(sgstamount,0) as sgst,
                                (coalesce(cgstamount,0) + coalesce(sgstamount,0)) as totalTaxAmount,
                                sum(b.qty) as totalqty,
                                RTRIM(
                                    CASE 
                                        WHEN cashamount > 0 
                                        THEN 'Cash,' 
                                        ELSE '' 
                                    END ||

                                    CASE 
                                        WHEN creditamount > 0 
                                        THEN 'Card,' 
                                        ELSE '' 
                                    END ||

                                    CASE 
                                        WHEN onlineamount > 0 
                                        THEN 'Online-UPI,' 
                                        ELSE CASE WHEN onlineorders !='' THEN 'Others' ELSE '' END 
                                    END ||

                                    CASE 
                                        WHEN creditcustomeramount > 0 
                                        THEN 'Credit,' 
                                        ELSE '' 
                                    END
                                , ',') AS payment_type

                                from tblsales as a
                                inner join tblsalesitemdetails as b on b.transactiondate=a.transactiondate and b.voucherno=a.voucherno and b.branchcode=a.branchcode
                                where a.branchcode = $branchcode and 
                                to_char(to_timestamp(a.transactiondate/1000),'yyyy-mm-dd') between '$fromdate' and '$todate' 
                                group by a.createddate,a.voucherno, a.transactiondate,gross_sales_amount,netamount,salestime,discount,mobilenumber,customername,cgst,sgst,totalTaxAmount, a.cashamount, a.creditamount, a.onlineamount,a.onlineorders, a.creditcustomeramount
                                order by voucherno desc";

            $result = pg_query($con, $paraquery);
            if (!empty($result)) {
                if (pg_num_rows($result) > 0) {
                    // user node
                    $response["Value"] = array();
                
                    while ($row = pg_fetch_assoc($result)) {
                        $mil = $row["transactiondate"];
                        $seconds = ($mil / 1000);

                        $timemil = $row["createddate"];
                        $timeseconds = ($timemil / 1000);

                        $tax = $row["sgst"] + $row["cgst"];
                        $grand_total =$row["netamount"] - $tax;
                        $report = array();
                        
                        $report["LOCATION_CODE"] = "01";
                        $report["TERMINAL_ID"] = "01";
                        $report["SHIFT_NO"] = "01";
                        $report["RCPT_NUM"] = $row["voucherno"];
                        $report["RCPT_DT"] = date("Ymd ",$seconds);
                        $report["BUSINESS_DT"] = date("Ymd",$seconds);
                        $report["RCPT_TM"] = date("His",$timeseconds);
                        $report["INV_AMT"] = $row["netamount"];
                        $report["TAX_AMT"] = sprintf('%0.2f', $tax);
                        $report["RET_AMT"] = 0;
                        $report["TRN_STATUS"] = 'Sales';
                        $report["PAYMENT_NAME"] = $row["payment_type"];
                        $report["CURRENCY_CODE"] = 'INR';
                        $report["EXCHANGE_RATE"] = 0;
                        $report["TENDER_AMOUNT"] = $row["netamount"];
                        $report["OP_CUR"] = 'INR';
                        $report["BC_EXCH"] = 0;
                        $report["PAYMENT_STATUS"] = 'Sales';

                         
                        // push single product into final response array
                        array_push($response["Value"], $report);
                    }
                    // success
                    $response["success"] = 1;

                    // echoing JSON response
                    echo json_encode($response, JSON_UNESCAPED_SLASHES);
                } else {
                    // no user found
                    $response["success"] = 0;
                    $response["message"] = "No Report found";

                    // echo no users JSON
                    echo json_encode($response);
                }
            } else {
                // no user found
                $response["success"] = 0;
                $response["message"] = "No found";

                // echo no users JSON
                echo json_encode($response);
            }
        } else {
            // required field is missing
            $response["success"] = 0;
            $response["message"] = "Required field(s) is missing";

            echo json_encode($response, JSON_UNESCAPED_UNICODE);
        }
        pg_close($con);
    } catch(Exception $e) {
        pg_close($con);
        echo 'Message: ' .$e->getMessage();
    }
?>