<?php
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include('includes/function.php');

$zdb = $_SESSION["zdbyear_" . $dbname];
$admin = $_SESSION["admin_" . $dbname];

//$zroot = 'cepheisy_msp_root';
$comp = $_SESSION["comp_" . $dbname];

$trandb = "actran";
$myear = $_SESSION["tit_" . $dbname];
mysqli_select_db($conn, $zdb);

if (isset($_POST["view"])) {
    $acond = "";
    $scond = "";
    if ($comp > 100) {
        $mpart = "party";
    } else {
        $mpart = "broker";
    }

    if (!empty($_POST["acname"])) {
        $accode = trim($_POST["acname"]);
        $acond = "AND a.`$mpart`='$accode'";
    }
    //    if (!empty($_POST["cmbstation"])) {
    //        $station = trim($_POST["cmbstation"]);
    //        $scond = "AND a.`station`='$station'";
    //    }

    // $invdtcond = "";
    // $invdtcond2 = "";

    $mtodate = $_POST["frmdt"];

    if ($_POST["hiddenval"] == "R") {
        $mfile = "rawmain";
        $mfile2 = "gstmain";
        $mtype = "S";
        $mdate = 'invdt';
        $blsrc1 = 'SLM';
        $blsrc2 = 'SLFP';
        $fintot = "netamt";
        $grid = "osbill.php?para=R";
        $formname1 = "Outstanding Receivable";
        $agency = $_POST["agency"];
        $agenqry = mysqli_query($conn, "SELECT name from accmast WHERE `accode` = '$agency' ") or die(mysqli_error($conn));
        $agenfet = mysqli_fetch_array($agenqry);
        $agenname = $agenfet['name'];

        $frminvdt = $_POST["frminvdt"];
        $toinvdt = $_POST["toinvdt"];

        if ($frminvdt != "" && $toinvdt != "") {
            if ($frminvdt == "0000-00-00" && $toinvdt == "0000-00-00"){
                $invdtcond = "";
                $invdtcond2 = "";
            }else{
                $invdtcond = "AND $mdate >= '$frminvdt' AND $mdate <= '$toinvdt' ";
                $invdtcond2 = "AND billdate >= '$frminvdt' AND billdate <= '$toinvdt'";
            }
        }
    } else {
        $mfile = 'purrawmain';
        $mfile2 = "pgstmain";
        $blsrc1 = 'PUM';
        $blsrc2 = 'PUFP';
        $mtype = "P";
        $mdate = 'vouchdt';
        $fintot = "netamt";
        $grid = "osbill.php?para=P";
        $formname1 = "Outstanding Payable";
        $agency = '';
        $agenname = '';

        
        $frminvdt = $_POST["frminvdt"];
        $toinvdt = $_POST["toinvdt"];


        if ($frminvdt != "" && $toinvdt != "") {
            if ($frminvdt == "0000-00-00" && $toinvdt == "0000-00-00"){
                $invdtcond = "";
                $invdtcond2 = "";
            }else{
                $invdtcond = "AND $mdate >= '$frminvdt' AND $mdate <= '$toinvdt' ";
                $invdtcond2 = "AND billdate >= '$frminvdt' AND billdate <= '$toinvdt'";
            }
        }
    }
    if ($_POST["dtype"] == 1) {
        $formname = "$formname1 - Summary";
        $dtype = 1;
    } else {
        $formname = "$formname1 - Detail";
        $dtype = 2;
    }

    include("includes/linkshead.php");

    $mtdt = date("d-m-Y", strtotime($mtodate));
    ?>
    <link href="MyStyle/rep_format.css" rel="stylesheet">

    <style>
        .report {
            margin-top: 0px;
        }
        #tabital {
            font-style: italic;
        }

        #font1 {
            font-style: italic;
        }

        #boldfont {
            font-weight: bold;
        }

        /* .report tr td {
            padding-right: 10px;
            font-size: 18px;
        } */
    </style>
    </head>

    <body>
        <div class="row" style="margin-top: 15px;">
            <div class="col-lg-6" style="width:100%;padding-left: 7%;padding-right: 4%">
                <div class="box">
                    <?php include("includes/head_rep.php"); ?>
                    <div id="sortableTable" class="body collapse in">
                        <table style="width:100%;" id="" class="table table-condensed table-bordered ">
                            <thead>
                                <?php if ($agency != '') { ?>
                                    <tr class="mySearchTr">
                                        <th style="" colspan="6">Agency : <?php echo $agenname ?></th>
                                    </tr>
                                <?php }
                                ?>

                                <tr class="mySearchTr">
                                    <th style="text-align:center" colspan="5">Name</th>
                                    <th style="text-align: right;">Amount</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $agencond = '';
                                if ($mtype == 'S') {
                                    if ($agency != '') {
                                        $agencyflag = 'Y';
                                        $agencond = " and b.broker = '$agency' ";
                                    } else {
                                        $agencyflag = 'N';
                                    }
                                } else {
                                    $agencyflag = 'N';
                                }

                                if ($agencyflag == 'N') {
                                    $acc = mysqli_query($conn, "SELECT a.$mpart as party, b.name,b.add1,b.add2,b.add3,b.mobile,b.city,b.pin FROM `$mfile` a, accmast b WHERE a.vouchno != '' AND a.$mpart  = b.accode and a.vouchdt <= '$mtodate' $acond GROUP BY a.party
                                                                union
                                                                SELECT a.$mpart as party, b.name,b.add1,b.add2,b.add3,b.mobile,b.city,b.pin FROM `$mfile2` a, accmast b WHERE a.vouchno != '' AND a.$mpart = b.accode and a.vouchdt <= '$mtodate' $acond GROUP BY a.party order by `name` ") or die(mysqli_error($conn));
                                } else {

                                    $acc = mysqli_query($conn, "select * from 
                                                                    (SELECT a.$mpart as party, b.broker, b.name,b.add1,b.add2,b.add3,b.mobile,b.city,b.pin FROM `$mfile` a, accmast b WHERE a.vouchno != '' AND a.$mpart = b.accode 
                                                                        and a.vouchdt <= '$mtodate'   $agencond GROUP BY a.$mpart 
                                                                    union
                                                                    SELECT a.$mpart as party,  b.broker, b.name,b.add1,b.add2,b.add3,b.mobile,b.city,b.pin FROM `$mfile2` a, accmast b WHERE a.vouchno != '' AND a.$mpart = b.accode 
                                                                        and a.vouchdt <= '$mtodate'   $agencond GROUP BY a.$mpart )
                                                                    a order by name") or die(mysqli_error($conn));
                                }
                                //                                    print table($acc);
                                //                                    die();

                                while ($getac = mysqli_fetch_array($acc)) {

                                    $maccode = $getac["party"];
                                    $macname = $getac["name"];
                                    $madd1 = $getac["add1"];
                                    $madd2 = $getac["add2"];
                                    $madd3 = $getac["add3"];
                                    $mcity = $getac["city"];
                                    $mpin = $getac["pin"];
                                    $mmobile = $getac["mobile"];

                                    $sub1 = mysqli_query($conn, "SELECT  SUM($fintot) AS amt1 FROM $mfile WHERE `$mpart` = '$maccode' AND `cashcred` != 'C'  AND canc_flag!='C'  and vouchdt <= '$mtodate' $invdtcond ") or die(mysqli_error($conn));
                                    $msub1 = mysqli_fetch_array($sub1);

                                    $sub1_1 = mysqli_query($conn, "SELECT  SUM($fintot) AS amt1 FROM $mfile2 WHERE `$mpart` = '$maccode' AND `cashcred` != 'C'  AND canc_flag!='C'  and vouchdt <= '$mtodate' $invdtcond ") or die(mysqli_error($conn));
                                    $msub1_1 = mysqli_fetch_array($sub1_1);

                                    $sub2 = mysqli_query($conn, "SELECT  SUM(`billamt`) AS amt2 FROM `prevbill` WHERE `accode` = '$maccode' AND `cashcred` != 'C'  and billdate <= '$mtodate' $invdtcond2 ") or die(mysqli_error($conn));
                                    $msub2 = mysqli_fetch_array($sub2);
                                    $msamt1 = $msub1["amt1"];
                                    $msamt1_1 = $msub1_1["amt1"];

                                    $msamt2 = $msub2["amt2"];
                                    $qamt1 = $msamt1_1 + $msamt1 + $msamt2;


                                    $trn1 = mysqli_query($conn, "SELECT SUM(setoff) AS setoff FROM `billsett` WHERE  `party`= '$maccode' AND `type`='$mtype'") or die(mysqli_error($conn));
                                    $gtrn1 = mysqli_fetch_object($trn1);
                                    $msetoff1 = $gtrn1->setoff;

                                    $mbalamt1 = $qamt1 - $msetoff1;


                                    if ($mbalamt1 > 0) {
                                        echo "<tr>";
                                        echo "<td colspan='5' style=\"text-align:center;\"><b>" . strtoupper($macname) . "</b></td>";
                                        echo "<td style=\"text-align:right;\">";
                                        echo "$mbalamt1";
                                        echo "</td>";
                                        echo "</tr>";
                                        echo "<tr>";
                                        echo "<td colspan='6' style=\"text-align:left;font-size:13px\">Address: $madd1 $madd2 $madd3 $mcity $mpin &nbsp;&nbsp;&nbsp;&nbsp;   Mobile: $mmobile </td>";
                                        echo "</tr>";

                                        if ($dtype == 2) {
                                            ?>

                                            <tr style="height:10px;" class="mySearchTr">
                                                <th align="left" width="15%">Date<i class="icon-sort"></i><i class="icon-sort-down"></i> <i class="icon-sort-up"></i></th>
                                                <th align="left" width="15%">Bill No.<i class="icon-sort"></i><i class="icon-sort-down"></i> <i class="icon-sort-up"></i></th>
                                                <th align="right" width="20%" style="text-align:right;">Bill Amount<i class="icon-sort"></i><i class="icon-sort-down"></i> <i class="icon-sort-up"></i></th>
                                                <th align="right" width="20%" style="text-align:right;">Recd. Amount<i class="icon-sort"></i><i class="icon-sort-down"></i> <i class="icon-sort-up"></i></th>
                                                <th align="right" width="20%" style="text-align:right;">Balance<i class="icon-sort"></i><i class="icon-sort-down"></i> <i class="icon-sort-up"></i></th>
                                                <th align="right" width="9%" style="text-align:right;">Days<i class="icon-sort"></i><i class="icon-sort-down"></i> <i class="icon-sort-up"></i></th>
                                            </tr>
                                            <?php
                                            $subtmp1 = mysqli_query($conn, "Select * from 
                                                                (SELECT '$myear' AS `yearno`, '$mtype' AS `type`, `vouchno`, `invno` as billno,$mdate as tdt,
                                                                        DATE_FORMAT($mdate, '%d-%m-%Y') AS `billdate`,  `$fintot` as billamt, `$mpart` as accode , '$blsrc1' as billsrc
                                                                        FROM $mfile WHERE `$mpart` = '$maccode' AND `cashcred` != 'C' AND canc_flag!='C' and vouchdt <= '$mtodate' $invdtcond
                                                                UNION
                                                                SELECT '$myear' AS `yearno`, '$mtype' AS `type`, `vouchno`, `invno` as billno,$mdate as tdt,
                                                                        DATE_FORMAT($mdate, '%d-%m-%Y') AS `billdate`,  `$fintot` as billamt, `$mpart` as accode , '$blsrc2' as billsrc
                                                                        FROM $mfile2 WHERE `$mpart` = '$maccode' AND `cashcred` != 'C' AND canc_flag!='C' and vouchdt <= '$mtodate' $invdtcond
                                                                UNION
                                                                SELECT `yearno`,`type`,`vouchno`, `billno`, billdate as tdt, DATE_FORMAT(`billdate`, '%d-%m-%Y') AS 
                                                                       `billdate`, `billamt`, `accode`, 'PB' as billsrc FROM `prevbill` WHERE `accode` = '$maccode' $invdtcond2
                                                                        AND `type` = '$mtype' ) a order by tdt,billno ") or die(mysqli_error($conn));
//                                            print table($subtmp1);
                                            $totbillamt = 0;
                                            $totrecdamt = 0;
                                            $totbalamt = 0;


                                            while ($murl = mysqli_fetch_object($subtmp1)) {

                                                $qyear = $murl->yearno;
                                                $qbilldate = $murl->billdate;
                                                $qbill = $murl->billno;
                                                $qvouch = $murl->vouchno;
                                                $qamt = $murl->billamt;
                                                $qparty = $murl->accode;
                                                $qbillsrc = $murl->billsrc;

                                                $date1 = date_create("$qbilldate");
                                                $date2 = date_create("$mtodate");
                                                $diff = date_diff($date1, $date2);
                                                $subtdate = $diff->format("%a");
                                                $mldays = $subtdate;

                                                $trn = mysqli_query($conn, "SELECT SUM(setoff) AS setoff FROM `billsett` WHERE  `party`= '$qparty' AND `yearno` ='$qyear' AND 
                                                                       `vouchno`='$qvouch' AND `type`='$mtype' and `billsrc` = '$qbillsrc' ") or die(mysqli_error($conn));
//                                                print table($trn);

                                                $gtrn = mysqli_fetch_object($trn);

                                                $msetoff = $gtrn->setoff;
                                                $mbalamt = $qamt - $msetoff;

                                                if ($mbalamt > 0) {
                                                    $totbillamt = $totbillamt + $qamt;
                                                    $totrecdamt = $totrecdamt + $msetoff;
                                                    $totbalamt = $totbalamt + $mbalamt;
                                                    echo "<tr style='height:20px;'>";
                                                    echo "<td style=\"text-align:left;\" scope=\"col\" width=\"300\">$qbilldate</td>";
                                                    echo "<td style=\"text-align:left;\" scope=\"col\" width=\"100\">$qbill</td>";
                                                    echo "<td style=\"text-align:right;\" scope=\"col\" width=\"300\">$qamt</td>";
                                                    echo "<td style=\"text-align:right;\" scope=\"col\" width=\"200\">$msetoff</td>";
                                                    echo "<td style=\"text-align:right;\" scope=\"col\" width=\"200\">$mbalamt</td>";
                                                    echo "<td style=\"text-align:right;\" scope=\"col\" width=\"200\">$mldays</td>";
                                                    echo "</tr>";
                                                }
                                            }
                                            echo "<tr style='height:20px;background-color: #ced4da'>";
                                            echo "<td style=\"text-align:left;\" scope=\"col\" width=\"300\"></td>";
                                            echo "<td style=\"text-align:right;\" scope=\"col\" width=\"100\"><b>Total</b></td>";
                                            echo "<td style=\"text-align:right;\" scope=\"col\" width=\"300\"><b>$totbillamt</b></td>";
                                            echo "<td style=\"text-align:right;\" scope=\"col\" width=\"200\"><b>$totrecdamt</b></td>";
                                            echo "<td style=\"text-align:right;\" scope=\"col\" width=\"200\"><b>$totbalamt</b></td>";
                                            echo "<td style=\"text-align:right;\" scope=\"col\" width=\"200\"></td>";
                                            echo "</tr>";
                                            echo "<tr style='height:20px;'>";
                                            echo "<td style=\"text-align:left;\" scope=\"col\" width=\"300\"></td>";
                                            echo "<td style=\"text-align:right;\" scope=\"col\" width=\"100\"></td>";
                                            echo "<td style=\"text-align:right;\" scope=\"col\" width=\"100\"></td>";
                                            echo "<td style=\"text-align:right;\" scope=\"col\" width=\"100\"></td>";
                                            echo "<td style=\"text-align:right;\" scope=\"col\" width=\"100\"></td>";
                                            echo "<td style=\"text-align:right;\" scope=\"col\" width=\"200\"></td>";
                                            echo "</tr>";
                                        }
                                    }
                                }
                                ?>

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    if (isset($_POST["excel"])) {
        $acond = "";
        $scond = "";

        if (!empty($_POST["acname"])) {
            $accode = trim($_POST["acname"]);
            $acond = "AND a.`broker`='$accode'";
        }

        $mtodate = $_POST["frmdt"];

        if ($_POST["hiddenval"] == "R") {
            $mfile = "salemain";
            $mtype = "S";
            $mdate = 'invdt';
            $fintot = "netamt";
            $grid = "osbill.php?para=R";
            $formname1 = "Outstanding Receivable";
        } else {
            $mfile = "purmain";
            $mtype = "P";
            $mdate = 'vouchdt';
            $fintot = "netamt";
            $grid = "osbill.php?para=P";
            $formname1 = "Outstanding Payable";
        }
        if ($_POST["dtype"] == 1) {
            $formname = "$formname1 - Summary";
            $dtype = 1;
        } else {
            $formname = "$formname1 - Detail";
            $dtype = 2;
        }



        $mtdt = date("d-m-Y", strtotime($mtodate));

        $contents .= "Name,Amount,\n";

        $acc = mysqli_query($conn, "SELECT a.*, b.name FROM `$mfile` a, accmast b WHERE a.vouchno != '' AND a.party = b.accode $acond GROUP BY a.party order by b.name") or die(mysqli_error($conn));
        while ($getac = mysqli_fetch_array($acc)) {

            $maccode = $getac["party"];
            $macname = $getac["name"];

            $sub1 = mysqli_query($conn, "SELECT  SUM($fintot) AS amt1 FROM $mfile WHERE `party` = '$maccode' AND `cashcred` != 'C'") or die(mysqli_error($conn));

            $sub2 = mysqli_query($conn, "SELECT  SUM(`billamt`) AS amt2 FROM `prevbill` WHERE `accode` = '$maccode' AND `cashcred` != 'C'") or die(mysqli_error($conn));
            $msub1 = mysqli_fetch_array($sub1);
            $msub2 = mysqli_fetch_array($sub2);
            $msamt1 = $msub1["amt1"];

            $msamt2 = $msub2["amt2"];
            $qamt1 = $msamt1 + $msamt2;


            $trn1 = mysqli_query($conn, "SELECT SUM(setoff) AS setoff FROM `billsett` WHERE  `party`= '$maccode' AND `type`='$mtype'") or die(mysqli_error($conn));
            $gtrn1 = mysqli_fetch_object($trn1);
            $msetoff1 = $gtrn1->setoff;

            $mbalamt1 = $qamt1 - $msetoff1;


            if ($mbalamt1 > 0) {

                $contents .= strtoupper($macname) . ",";
            }
            $contents .= $mbalamt1 . "\n";

            if ($dtype == 2) {

                $contents .= "Date,Bill No.,Bill Amount,Recd. Amount,Balance,Days,\n";

                $subtmp1 = mysqli_query($conn, "SELECT '$myear' AS `yearno`, '$mtype' AS `type`, `vouchno`, `invno` as billno,
                                                                DATE_FORMAT($mdate, '%d-%m-%Y') AS `billdate`,  `$fintot` as billamt, `party` as accode 
                                                                FROM $mfile WHERE `party` = '$maccode' AND `cashcred` != 'C' 
                                                                UNION
                                                                SELECT `yearno`,`type`,`vouchno`, `billno`, DATE_FORMAT(`billdate`, '%d-%m-%Y') AS 
                                                               `billdate`, `billamt`, `accode` FROM `prevbill` WHERE `accode` = '$maccode' 
                                                                AND `type` = '$mtype'") or die(mysqli_error($conn));
                $totbillamt = 0;
                $totrecdamt = 0;
                $totbalamt = 0;

                while ($murl = mysqli_fetch_object($subtmp1)) {

                    $qyear = $murl->yearno;
                    $qbilldate = $murl->billdate;
                    $qbill = $murl->billno;
                    $qvouch = $murl->vouchno;
                    $qamt = $murl->billamt;
                    $qparty = $murl->accode;


                    $dt1 = date_create($mtodate);
                    $dt2 = date_create($qbilldate);
                    $subtdate = $dt1 - $dt2;
                    $mldays = $subtdate;


                    $trn = mysqli_query($conn, "SELECT SUM(setoff) AS setoff FROM `billsett` WHERE  `party`= '$qparty' AND `yearno` ='$qyear' AND 
                                                                       `vouchno`='$qvouch' AND `type`='$mtype'") or die(mysqli_error($conn));

                    $gtrn = mysqli_fetch_object($trn);

                    $msetoff = $gtrn->setoff;
                    $mbalamt = $qamt - $msetoff;

                    if ($mbalamt > 0) {
                        $totbillamt = $totbillamt + $qamt;
                        $totrecdamt = $totrecdamt + $msetoff;
                        $totbalamt = $totbalamt + $mbalamt;
                        $contents .= $qbilldate . ",";
                        $contents .= $qbill . ",";
                        $contents .= $qamt . ",";
                        $contents .= $msetoff . ",";
                        $contents .= $mbalamt . ",";
                        $contents .= $mldays . "\n";
                    }
                }

                $contents .= " " . ",";
                $contents .= "Total" . ",";
                $contents .= $totbillamt . ",";
                $contents .= $totrecdamt . ",";
                $contents .= $totbalamt . ",";
                $contents .= " " . "\n";
            }
        }
        $contents = strip_tags($contents);

        if ($_POST["dtype"] == 1) {
            header("Content-Disposition: attachment; filename=$formname" . "_Summary" . date('d-m-Y') . ".csv");
            print $contents;
        } else {
            header("Content-Disposition: attachment; filename=$formname" . "_Detail" . date('d-m-Y') . ".csv");
            print $contents;
        }
    }
    ?>