<?php
ini_set('display_errors', 1);
error_reporting(E_ERROR);

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

$zdb = $_SESSION["zdbyear_" . $dbname];
$admin = $_SESSION["admin_" . $dbname];
$zcompany = $_SESSION["zcompany"];
$formname = "Aaya Gaya";

$grid = "cashinoutrep.php";
$cust = "accmast";
$ztit = $_SESSION["tit_" . $dbname];
$zroot = $_SESSION["zdir"];
$maindb = $cust;
$accdb = "actran";

$fseries = $_SESSION["series"];
$keycond = "";
$abal = 'accmtn';
$accbal = $abal . $ztit;
$compcond = '';

//if (isset($_POST["view"])) {
$a = 1;

$mfrmdate = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
$mtodate = $mfrmdate;
$mname1 = trim($_REQUEST["accode"]);

if ($mfrmdate == "" && $mtodate == "") {
    $mfrmdate = date("Y-m-d");
    $mtodate = date("Y-m-d");
}

$mfdt = $mfrmdate;
$mtdt = $mtodate;

//if ($mfrmdate > $mtodate) {
//    browse("To Date Cannot Be Less Than From Date");
//    header("refresh: 1; ledger_new.php");
//    exit();
//    $a = 0;
//}
//$maccode = '';
//if ($mname1 == '') {
//    browse("A/c. Name Cannot Be Empty");
//    header("refresh: 1; ledger_new.php");
//    exit();
//    $a = 0;
//} else {
//    $maccode = $mname1;
//}
$paytypecond = '';
if (!empty($_POST["paytype"])) {
    $paytype = trim($_POST["paytype"]);
    $paytypecond = "AND `paytype`='$partytype'";
}


$zyear = right($zdb, 4);
//$mfrmdate = getzdates($zyear, 'S', $conn);
//$mtodate = getzdates($zyear, 'E', $conn);
mysqli_select_db($conn, $zdb);

//if ($a == 1) {
$recqry = mysqli_query($conn, " SELECT *, DATE_FORMAT(`date`, '%d-%m-%Y') AS vouchdt  FROM `$accdb`
                                where amount < 0 and chqret != 'Y' and accode = '3'
                                and date = '$mfrmdate' and source in ('CR','TR')
                                order by date, source, vouchno ") or die(mysqli_error($conn));
$rcount = mysqli_num_rows($recqry);

$payqry = mysqli_query($conn, " SELECT *, DATE_FORMAT(`date`, '%d-%m-%Y') AS vouchdt  FROM `$accdb`
                                where amount > 0 and chqret != 'Y' and accode = '3'
                                and date = '$mfrmdate' and source in ('CP' ,'TR')
                                order by date, source, vouchno ") or die(mysqli_error($conn));
$lcount = mysqli_num_rows($payqry);

$getopen = mysqli_query($conn, "SELECT grpcode, accode, name, openbal, dc  FROM `$maindb` WHERE  accode = '3' ") or die(mysqli_error($conn));

$ctr = 0;
$totrecp = 0;
$fetopen = mysqli_fetch_array($getopen);
$mname = $fetopen['name'];

$opdc = $fetopen["dc"];

if ($opdc == 'D') {
    $opb = $fetopen["openbal"] * -1;
} else {
    $opb = $fetopen["openbal"];
}
$opbt = $opb;
$mopen = $opbt;

$getacc = mysqli_query($conn, "SELECT SUM(amount) AS `openamt` FROM `$accdb` WHERE accode = '3' and `date` < '$mfrmdate' and chqret != 'Y' ") or die(mysqli_error($conn));
$fetacc = mysqli_fetch_array($getacc);
$openacc = $fetacc['openamt'];

$finopen = $mopen + $openacc;
$finop = abs($finopen);

$getacc2 = mysqli_query($conn, "SELECT SUM(amount) AS `openamt` FROM `$accdb` WHERE accode = '3' and `date` <= '$mtodate' and chqret != 'Y' $compcond $keycond") or die(mysqli_error($conn));
$fetacc2 = mysqli_fetch_array($getacc2);
$openacc2 = $fetacc2['openamt'];

$finclos = $mopen + $openacc2;
$fincl = abs($finclos);

include("includes/linkshead.php");
?>
<style>
    @media print {
        a {
            text-decoration: none;
            /* Remove the underline */
            color: black;
            /* Change the color to black */
        }

        a[href]:after {
            content: none;
            /* Hide the href */
        }

        table td {
            font-size: 10px;
        }
    }

    .noprint {
        margin-top: 5px;
        border: 2px solid;
        border-radius: 10px;
    }

    .noprint1 {
        margin-top: 5px;
        border: 2px solid;
        border-radius: 10px;
    }

    .intbtn {
        color: black;
        text-transform: uppercase;
        text-decoration: none;
        border: 2px solid green;
        border-radius: 5px;
        padding: 10px 20px;
        font-size: 17px;
        font-weight: bold;
        background: transparent;
        position: relative;
        transition: all 1s;
        overflow: hidden;
    }

    .intbtn:hover {
        color: white;
    }

    .intbtn::before {
        content: '';
        position: absolute;
        height: 100%;
        width: 0%;
        top: 0;
        left: -40px;
        transform: skewX(45deg);
        background-color: #963634;
        z-index: -1;
        transition: all 1s;
    }

    .intbtn:hover::before {
        width: 160%;
    }
</style>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $("body").on("click", ".intbtn", Deposit);
        $("body").on("click", ".savdep", savDeposit);


        function savDeposit() {
            var formData = {};
            // Iterate over all visible input, textarea, and select fields
            $('.depModal input, textarea, select').filter(':visible').each(function () {
                var fieldName = $(this).attr('name');
                var fieldValue;
                var fieldType = $(this).attr('type'); // Get the type of the field


                // Only add to the object if the field has a name attribute

                if (fieldType === 'checkbox' || fieldType === 'radio') {
                    // For checkboxes and radios, check if they are checked
                    fieldValue = $(this).is(':checked') ? $(this).val() : null;
                } else {
                    // For other fields (text, textarea, select), get the value directly
                    fieldValue = $(this).val();
                }
                if (fieldName && fieldValue !== null) {
                    formData[fieldName] = fieldValue;
                }
            });

            // Convert the object to JSON format
            var jsonData = JSON.stringify(formData);
            var newv = 0;
            $.ajax({
                //                url: 'addhtrtcrd.php', // Replace with your server URL
                url: 'saveAgentIn.php', // Replace with your server URL
                type: 'POST',
                contentType: 'application/json',
                data: jsonData,
                success: function (response) {
                    var m = response;
                    if (m.success == true) {

                        newv = m.vouchno;
                        $(".vouchno").val(m.vouchno);
                        if (newv > 0) {
                            location.reload();
                        }
                        event.preventDefault();
                    }
                },
                error: function (xhr, status, error) {
                    console.error('Error:', status, error);
                }
            });
            //            alert(jsonData);
        }

        function Deposit() {
            $(".depModal").modal("show");
            var depwit = $(this).val();
            $(".para").val(depwit);
            if (depwit == "I") {
                $(".inttrd").show();
                $(".deptrd").hide();
                $(".wittrd").hide();
                $(".trdint").show();
                $("#myLargeModalLabel1").hide();
                $("#myLargeModalLabel2").hide();
                $("#myLargeModalLabel3").show();

            }
        }

        $("#prevDate").click(function () {
            let d = new Date($("#selDate").val());
            d.setDate(d.getDate() - 1);

            let newDate = d.toISOString().split('T')[0];
            location.href = "?date=" + newDate;
        });

        $("#nextDate").click(function () {
            let d = new Date($("#selDate").val());
            d.setDate(d.getDate() + 1);

            let newDate = d.toISOString().split('T')[0];
            location.href = "?date=" + newDate;
        });

        $("#selDate").change(function () {
            location.href = "?date=" + $(this).val();
        });
    })
</script>
<script>
    function saveAsPDF() {
        const element = document.getElementById('content-to-save');
        // Get the invoice number from an element
        const vouchno = document.getElementById('vouchno')?.textContent || 'NoINV';

        html2pdf()
                .set({
                    margin: 0,
                    filename: `CASHBOOKPDF.pdf`, // Dynamically set filename
                    image: {
                        type: 'jpeg',
                        quality: 0.98
                    },
                    html2canvas: {
                        scale: 3
                    }, // Increase scale for better quality and fit
                    jsPDF: {
                        unit: 'in',
                        format: 'a4',
                        orientation: 'landscape'
                    }
                })
                .from(element)
                .save();
    }
</script>
</head>

<body>

    <div class="container">
        <div class="col-lg-2 col-md-1 col-sm-3 col-xs-3 pad text-right">
            <!--<button type="button" class="intbtn noprint" value="I">Entry</button>-->
        </div>
        <!-- <button class="btn btn-primary goBack noprint" onclick="window.close()" style="float: right;width: 150px;height:35px;background-color: white;color:#A0B1BA;">Go Back</button> -->
        <button class="btn btn-primary noprint1" onclick="saveAsPDF()"
                style="float: right;width: 150px;height:35px;background-color: #40916c;color:#ffffff;">PDF</button>
        <div id="content-to-save">
            <div class="row">
                <div class="col-lg-6" style="width:100%;">
                    <div class="box">
                        <?php
//                    include("includes/head_rep.php");
                        ?>

                        <table width="100%">
                            <tr>
                                <th colspan="2" style="text-align:left;padding:10px;">
                                    <div style="display:flex;align-items:center;gap:10px;">

                                        <span style="font-size:18px;font-weight:700;color:#212529;">
                                            <?= $mname ?>
                                        </span>

                                        <button type="button" id="prevDate" class="btn btn-primary btn-sm">
                                            ◀
                                        </button>

                                        <div style="
                                             border:2px solid #0d6efd;
                                             border-radius:8px;
                                             padding:4px 10px;
                                             background:#f8f9fa;
                                             display:flex;
                                             align-items:center;
                                             gap:8px;
                                             ">
                                            <span style="
                                                  font-size:16px;
                                                  font-weight:bold;
                                                  color:#0d6efd;
                                                  ">
                                                📅
                                            </span>

                                            <input type="date"
                                                   id="selDate"
                                                   value="<?= $mfrmdate ?>"
                                                   style="
                                                   border:none;
                                                   background:transparent;
                                                   font-size:16px;
                                                   font-weight:bold;
                                                   color:#212529;
                                                   outline:none;
                                                   ">
                                        </div>

                                        <button type="button" id="nextDate" class="btn btn-primary btn-sm">
                                            ▶
                                        </button>

                                    </div>
                                </th>
                            </tr>
                            <tr>
                                <td width="50%" style="float:left">
                                    <table style="background: white;float:right" class="table  table-bordered" style="width:100%">
                                        <thead class="mySearchTr" style="background-color: #8d99ae;">
                                            <tr style="border:2px">
                                                <th colspan="6" style="font-size: 16px">Aaya</th>
                                            </tr>

                                            <tr style="border:2px;background:#40916c">
                                                <th width="15%">Date</th>
                                                <th width="4%">Source</th>
                                                <th width="8%">Voucher</th>
                                                <th width="20%">In</th>
                                                <th width="20%">From A/c</th>
                                                <th width="18%" class="text-right">Amount</th>
                                            </tr>
                                        </thead>

                                        <tbody>
                                            <?php
                                            $openflag = 0;
                                            if ($finopen <= 0) {
                                                $ctr++;
                                                echo "<tr>";
                                                echo "<td></td>";
                                                echo "<td></td>";
                                                echo "<td>Opening</td>";
                                                echo "<td></td>";
                                                echo "<td></td>";
                                                echo "<td class='text-right'>$finop</td>";
                                                echo "</tr>";

                                                $totrecp = $totrecp + $finop;
                                                $openflag = 1;
                                            } else {
                                                if ($lop == 1) {
                                                    echo "<tr>";
                                                    echo "<td></td>";
                                                    echo "<td></td>";
                                                    echo "<td></td>";
                                                    echo "<td>&nbsp;</td>";
                                                    echo "<td>&nbsp;</td>";
                                                    echo "<td></td>";
                                                    echo "</tr>";
                                                }
                                            }

                                            $ctr = 0;
                                            while ($receipt = mysqli_fetch_array($recqry)) {
                                                $source = $receipt['source'];
                                                $vouchno = $receipt['vouchno'];
                                                $vouchdt = $receipt['vouchdt'];
                                                $grpcode = $receipt['grpcode'];
                                                $recamt = abs($receipt['amount']);
                                                $amt = $receipt['amount'];

                                                $colr = "";
                                                $acname = '';

                                                if ($source == 'PYIN') {
                                                    $url = "payin.php?vouchno=$vouchno&mode=edit";
                                                    $url2 = "payin_fr.php?vouchno=$vouchno";
                                                    $desc = "Payment In";

                                                    if ($grpcode == '002') {
                                                        $getcash = mysqli_query($conn, "Select party as accode from `cashrecp` where `vouchno`='$vouchno' $compcond $keycond") or die(mysqli_error($conn));
                                                    } else {
                                                        $getcash = mysqli_query($conn, "Select bankname as accode from `cashrecp` where `vouchno`='$vouchno' $compcond $keycond") or die(mysqli_error($conn));
                                                    }
                                                    $fetcash = mysqli_fetch_array($getcash);
                                                    $accode = $fetcash['accode'];

                                                    $getacc = mysqli_query($conn, "Select name from `accmast` where `accode`='$accode' ") or die(mysqli_error($conn));
                                                    $fetacc = mysqli_fetch_array($getacc);
                                                    $desc = $fetacc['name'];
                                                }

                                                if ($source == 'CR') {
                                                    $url = "cashrecp.php?vouchno=$vouchno&mode=edit";
                                                    $url2 = "cashrecp_fr.php?vouchno=$vouchno";
                                                    $desc = "Receipt";

//                                                    if ($grpcode == '002') {
                                                    $getcash = mysqli_query($conn, "Select party , bankname from `cashrecp` where `vouchno`='$vouchno' $compcond $keycond") or die(mysqli_error($conn));
//                                                    } else {
//                                                        $getcash = mysqli_query($conn, "Select bankname as accode from `cashrecp` where `vouchno`='$vouchno' $compcond $keycond") or die(mysqli_error($conn));
//                                                    }
                                                    $fetcash = mysqli_fetch_array($getcash);
                                                    $accode = $fetcash['party'];

                                                    $getacc = mysqli_query($conn, "Select name from `accmast` where `accode`='$fetcash[bankname]' ") or die(mysqli_error($conn));
                                                    $fetacc = mysqli_fetch_array($getacc);
                                                    $desc = $fetacc['name'];
                                                    $getacc2 = mysqli_query($conn, "Select name from `accmast` where `accode`='$accode' ") or die(mysqli_error($conn));
                                                    $fetacc2 = mysqli_fetch_array($getacc2);
                                                    $desc2 = $fetacc2['name'];
                                                }

                                                if ($source == 'TR') {
                                                    $url = "contra.php?vouchno=$vouchno&mode=edit";
                                                    $url2 = "contra_fr.php?vouchno=$vouchno";
                                                    $desc = "Transfer";

                                                    $getcash = mysqli_query($conn, "Select frombc , tobc from `contra` where `vouchno`='$vouchno' $compcond $keycond") or die(mysqli_error($conn));
                                                    $fetcash = mysqli_fetch_array($getcash);
                                                    $accode = $fetcash['frombc'];

                                                    $getacc = mysqli_query($conn, "Select name from `accmast` where `accode`='$fetcash[tobc]' ") or die(mysqli_error($conn));
                                                    $fetacc = mysqli_fetch_array($getacc);
                                                    $desc = $fetacc['name'];
                                                    $getacc2 = mysqli_query($conn, "Select name from `accmast` where `accode`='$accode' ") or die(mysqli_error($conn));
                                                    $fetacc2 = mysqli_fetch_array($getacc2);
                                                    $desc2 = $fetacc2['name'];
                                                }

                                                if ($source == 'AG') {
                                                    $url = "inoutent.php?vouchno=$vouchno&mode=edit";
                                                    $url2 = "#";
                                                    $desc = "Aaya";

                                                    $getcash = mysqli_query($conn, "Select b.name from `inout` a, accmast b 
                                                                                       where a.`vouchno`='$vouchno' and a.frombc = b.accode ") or die(mysqli_error($conn));
                                                    $fetcash = mysqli_fetch_array($getcash);
                                                    $desc = $fetcash['name'];
                                                }

                                                if ($source == 'JV') {
                                                    $url = "jventry.php?vouchno=$vouchno&mode=edit";
                                                    $url2 = "jventry.php?vouchno=$vouchno";
                                                    $desc = "JV Entry";

                                                    if ($amt > 0) {
                                                        $getcash = mysqli_query($conn, "Select b.name from `jventry` a, accmast b where 
                                                                                           a.`vouchno`='$vouchno' and a.party = b.accode ") or die(mysqli_error($conn));
                                                    } else {
                                                        $getcash = mysqli_query($conn, "Select b.name from `jventry` a, accmast b where 
                                                                                           a.`vouchno`='$vouchno' and a.bankname = b.accode ") or die(mysqli_error($conn));
                                                    }
                                                    $fetcash = mysqli_fetch_array($getcash);
                                                    $desc = $fetcash['name'];
                                                }


                                                $ctr++;
                                                echo "<tr style='$colr' class='clickable-row2' data-href='$url' data-target='_blank'>";
                                                echo "<td>$vouchdt</td>";
                                                echo "<td>$source</td>";
                                                echo "<td><a href='$url2' target='_blank'>$vouchno</a></td>";
                                                echo "<td>$desc</td>";
                                                echo "<td>$desc2</td>";
                                                echo "<td class='text-right'>$recamt</td>";
                                                echo "</tr>";

                                                $totrecp = $totrecp + $recamt;
                                            }

                                            if ($rcount < $lcount) {
                                                $ext = $lcount - $rcount;
                                                for ($i = 0; $i < $ext; $i++) {
                                                    echo "<tr>";
                                                    echo "<td></td>";
                                                    echo "<td></td>";
                                                    echo "<td></td>";
                                                    echo "<td>&nbsp;</td>";
                                                    echo "<td></td>";
                                                    echo "<td></td>";
                                                    echo "</tr>";
                                                }
                                            }

                                            echo "<tr style='background:#95d5b2'>";
                                            echo "<td></td>";
                                            echo "<td></td>";
                                            echo "<td></td>";
                                            echo "<td></td>";
                                            echo "<td class='text-right' style'font-size:12px !important;'>Total</td>";
                                            echo "<td class='text-right' style'font-size:12px !important;'><b>$totrecp</b></td>";
                                            echo "</tr>";
                                            ?>
                                        </tbody>
                                    </table>
                                </td>

                                <td width="50%" style="float:right">
                                    <table style="background:white; width: 100%;" class="table table-bordered">
                                        <thead class="mySearchTr" style="background-color: #8d99ae;">

                                            <tr style="border:2px">
                                                <th colspan="6" style="font-size: 16px">Gaya</th>
                                            </tr>
                                            <tr style="border:2px;background:#40916c">
                                                <th width="15%">Date</th>
                                                <th width="4%">Source</th>
                                                <th width="8%">Voucher</th>
                                                <th width="20%">Out</th>
                                                <th width="20%">To A/c.</th>
                                                <th width="18%" class="text-right">Amount</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $lop = 0;
                                            if ($finopen > 0) {
                                                $ctr++;
                                                echo "<tr>";
                                                echo "<td></td>";
                                                echo "<td></td>";
                                                echo "<td>Opening</td>";
                                                echo "<td></td>";
                                                echo "<td></td>";
                                                echo "<td class='text-right'>$finop</td>";
                                                echo "</tr>";
                                                $lop = 1;
                                                $totpay = $totpay + $finop;
                                            }

                                            if ($openflag > 0) {
                                                echo "<tr>";
                                                echo "<td></td>";
                                                echo "<td></td>";
                                                echo "<td></td>";
                                                echo "<td></td>";
                                                echo "<td>&nbsp;</td>";
                                                echo "<td></td>";
                                                echo "</tr>";
                                            }
                                            ?>
                                            <?php
                                            $ctr2 = 0;
                                            $totpay = 0;

                                            while ($payment = mysqli_fetch_array($payqry)) {
                                                $source = $payment['source'];
                                                $vouchno = $payment['vouchno'];
                                                $vouchdt = $payment['vouchdt'];
                                                $payamt = abs($payment['amount']);
                                                $amt = $payment['amount'];
                                                $trcolr = "";

                                                if ($source == 'PYOU') {
                                                    $url = "payout.php?vouchno=$vouchno&mode=edit";
                                                    $url2 = "payout_fr.php?vouchno=$vouchno";
                                                    $desc = "Payment Out";

                                                    $mtransacdb = 'cashpay';

                                                    $getcash = mysqli_query($conn, "Select party as accode from `cashpay` where `vouchno`='$vouchno' $compcond $keycond") or die(mysqli_error($conn));
                                                    $fetcash = mysqli_fetch_array($getcash);
                                                    $accode = $fetcash['accode'];

                                                    $getacc = mysqli_query($conn, "Select name from `accmast` where `accode`='$accode' ") or die(mysqli_error($conn));
                                                    $fetacc = mysqli_fetch_array($getacc);
                                                    $desc = $fetacc['name'];
                                                }


                                                if ($source == 'CP') {
                                                    $url = "cashpay.php?vouchno=$vouchno&mode=edit";
                                                    $url2 = "cashpay_fr.php?vouchno=$vouchno";
                                                    $desc = "Payment";

//                                                    if ($grpcode == '002') {
                                                    $getcash = mysqli_query($conn, "Select party , bankname from `cashpay` where `vouchno`='$vouchno' $compcond $keycond") or die(mysqli_error($conn));
//                                                    } else {
//                                                        $getcash = mysqli_query($conn, "Select bankname as accode from `cashrecp` where `vouchno`='$vouchno' $compcond $keycond") or die(mysqli_error($conn));
//                                                    }
                                                    $fetcash = mysqli_fetch_array($getcash);
                                                    $accode = $fetcash['party'];

                                                    $getacc = mysqli_query($conn, "Select name from `accmast` where `accode`='$fetcash[bankname]' ") or die(mysqli_error($conn));
                                                    $fetacc = mysqli_fetch_array($getacc);
                                                    $desc = $fetacc['name'];
                                                    $getacc2 = mysqli_query($conn, "Select name from `accmast` where `accode`='$accode' ") or die(mysqli_error($conn));
                                                    $fetacc2 = mysqli_fetch_array($getacc2);
                                                    $desc2 = $fetacc2['name'];
                                                }

                                                if ($source == 'AG') {
                                                    $url = "#";
                                                    $url2 = "#";
                                                    $desc = "Gaya";

                                                    $getcash = mysqli_query($conn, "Select b.name from `inout` a, accmast b 
                                                                                       where a.`vouchno`='$vouchno' and a.tobc = b.accode ") or die(mysqli_error($conn));
                                                    $fetcash = mysqli_fetch_array($getcash);
                                                    $desc = $fetcash['name'];
                                                }

                                                if ($source == 'JV') {
                                                    $url = "jventry.php?vouchno=$vouchno&mode=edit";
                                                    $url2 = "jventry.php?vouchno=$vouchno";
                                                    $desc = "JV Entry";

                                                    if ($amt > 0) {
                                                        $getcash = mysqli_query($conn, "Select b.name from `jventry` a, accmast b where 
                                                                                           a.`vouchno`='$vouchno' and a.party = b.accode ") or die(mysqli_error($conn));
                                                    } else {
                                                        $getcash = mysqli_query($conn, "Select b.name from `jventry` a, accmast b where 
                                                                                           a.`vouchno`='$vouchno' and a.bankname = b.accode ") or die(mysqli_error($conn));
                                                    }
                                                    $fetcash = mysqli_fetch_array($getcash);
                                                    $desc = $fetcash['name'];
                                                }

                                                if ($source == 'TR') {
                                                    $url = "contra.php?vouchno=$vouchno&mode=edit";
                                                    $url2 = "contra_fr.php?vouchno=$vouchno";
                                                    $desc = "Transfer";

                                                    $getcash = mysqli_query($conn, "Select frombc , tobc from `contra` where `vouchno`='$vouchno' $compcond $keycond") or die(mysqli_error($conn));
                                                    $fetcash = mysqli_fetch_array($getcash);
                                                    $accode = $fetcash['tobc'];

                                                    $getacc = mysqli_query($conn, "Select name from `accmast` where `accode`='$fetcash[frombc]' ") or die(mysqli_error($conn));
                                                    $fetacc = mysqli_fetch_array($getacc);
                                                    $desc = $fetacc['name'];
                                                    $getacc2 = mysqli_query($conn, "Select name from `accmast` where `accode`='$accode' ") or die(mysqli_error($conn));
                                                    $fetacc2 = mysqli_fetch_array($getacc2);
                                                    $desc2 = $fetacc2['name'];
                                                }

                                                $ctr2++;
                                                echo "<tr style='$trcolr' class='clickable-row2' data-href='$url' data-target='_blank'>";
                                                echo "<td>$vouchdt</td>";
                                                echo "<td>$source</td>";
                                                echo "<td><a href='$url2' target='_blank'>$vouchno</a></td>";
                                                echo "<td>$desc</td>";
                                                echo "<td>$desc2</td>";
                                                echo "<td class='text-right'>$payamt</td>";
                                                echo "</tr>";

                                                $totpay = $totpay + $payamt;
                                            }

                                            if ($lcount < $rcount) {
                                                $ext = $rcount - $lcount;
                                                for ($i = 0; $i < $ext; $i++) {
                                                    echo "<tr>";
                                                    echo "<td></td>";
                                                    echo "<td></td>";
                                                    echo "<td></td>";
                                                    echo "<td></td>";
                                                    echo "<td>&nbsp;</td>";
                                                    echo "<td></td>";
                                                    echo "</tr>";
                                                }
                                            }

                                            echo "<tr style='background:#95d5b2'>";
                                            echo "<td></td>";
                                            echo "<td></td>";
                                            echo "<td></td>";
                                            echo "<td></td>";
                                            echo "<td class='text-right' style'font-size:12px !important;'>Total</td>";
                                            echo "<td class='text-right' style'font-size:12px !important;'><b>$totpay</b></td>";
                                            echo "</tr>";
                                            ?>
                                        </tbody>
                                    </table>
                                </td>
                            </tr>
                            <tr>


                            <table style="background: white;float:right" class="table  table-bordered" style="width:100%">

                                <?php
                                $diff = $totrecp - $totpay;

                                if ($diff > 0) {
                                    $ctr2++;
                                    ?>

                                    <thead class="mySearchTr">
                                        <tr style="border:2px;background:#40916c">
                                            <th width="11%">&nbsp;</th>
                                            <th width="3%">&nbsp;</th>
                                            <th width="3%">&nbsp;</th>
                                            <th width="24%" class="text-right">&nbsp;</th>
                                            <th width="9%" class="text-right">&nbsp;</th>
                                            <th width="11%">&nbsp;</th>
                                            <th width="3%">&nbsp;</th>
                                            <th width="3%">&nbsp;</th>
                                            <th width="24%" class="text-right">Balance</th>
                                            <th width="9%" class="text-right"><b><?= $diff ?></b></th>
                                        </tr>
                                    </thead>

                                <?php } else { ?>

                                    <thead class="mySearchTr">
                                        <tr style="border:2px;background:#40916c">
                                            <th width="11%">&nbsp;</th>
                                            <th width="3%">&nbsp;</th>
                                            <th width="3%">&nbsp;</th>
                                            <th width="24%" class="text-right">Balance</th>
                                            <th width="9%" class="text-right"><b><?= abs($diff) ?></b></th>
                                            <th width="11%">&nbsp;</th>
                                            <th width="3%">&nbsp;</th>
                                            <th width="3%">&nbsp;</th>
                                            <th width="24%">&nbsp;</th>
                                            <th width="9%" class="text-right">&nbsp;</th>
                                        </tr>
                                    </thead>
                                <?php } ?>
                            </table>
                            </tr>

                        </table>
                    </div>
                </div>
            </div>
        </div>
        <!--        <div class="modal fade depModal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content" style="width:80%">
                            <div class="modal-header">
                                <button class="close" data-dismiss="modal"><span>&times;</span></button>
                                <h4 class="modal-title" id="myLargeModalLabel3">Entry</h4>
                            </div>
                            <div class="modal-body">
                                <div class="row">
                                    <div class="col-lg-4 col-md-1 col-sm-4 col-xs-4 text-right">
                                        <label class="label-control">Date</label>
                                    </div>
                                    <div class="col-lg-4 col-md-3 col-sm-8 col-xs-8 pad">
                                        <input type="date" name="withdate" placeholder="date" value="<?php echo date('Y-m-d'); ?>"
                                               class="form-control withdate" style="height: 30px;" autofocus="autofocus">
                                    </div>
                                </div>
        
                                <div class="row inttrd">
                                    <div class="col-lg-4 col-md-3 col-sm-3 col-xs-3 text-right pad">
                                        <label class="label-control marg">From</label>
                                    </div>
                                    <div class="col-lg-6 col-md-6 col-sm-7 col-xs-7 pad">
                                        <select class="form-control select2" name="fragent" id="fragent" style='width:100%'>
                                            <option value=""></option>
        
        <?php
        $mfrag = mysqli_query($conn, "SELECT accode, `name` FROM `accmast` order by name") or die(mysqli_error($conn));
        while ($tfrag = mysqli_fetch_array($mfrag)) {
            echo "<option value='$tfrag[accode]'>$tfrag[name]</option>";
        }
        ?>
                                        </select>
                                    </div>
                                </div>
        
                                <div class="row inttrd">
                                    <div class="col-lg-4 col-md-3 col-sm-3 col-xs-3 text-right pad">
                                        <label class="label-control marg">To</label>
                                    </div>
                                    <div class="col-lg-6 col-md-6 col-sm-7 col-xs-7 pad">
                                        <select class="form-control select2" name="toagent" id="toagent" style='width:100%'>
                                            <option value=""></option>
        <?php
        $mtoag = mysqli_query($conn, "SELECT accode, `name` FROM `accmast` order by name") or die(mysqli_error($conn));
        while ($ttoag = mysqli_fetch_array($mtoag)) {
            echo "<option value='$ttoag[accode]'>$ttoag[name]</option>";
        }
        ?>
                                        </select>
                                    </div>
                                </div>
        
                                <div class="row wittrd trdint">
                                    <div class="col-lg-4 col-md-3 col-sm-3 col-xs-3 text-right pad">
                                        <label class="label-control marg">Amount</label>
        
                                    </div>
                                    <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 pad">
                                        <input type="text" name="amt" value="0" class="form-control  amt text-right">
                                    </div>
                                </div>
        
                                                        <div class="row wittrd trdint">
                                                            <div class="col-lg-4 col-md-3 col-sm-3 col-xs-3 text-right pad">
                                                                <label class="label-control marg">ROE</label>
                                                            </div>
                                                            <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 pad">
                                                                <input type="text" name="roe" value="0" class="form-control  droe text-right">
                                                            </div>
                                                        </div>
        
                                <div class="row wittrd trdint">
                                    <div class="col-lg-4 col-md-3 col-sm-3 col-xs-3 text-right pad">
                                        <label class="label-control marg">Remark</label>
                                    </div>
                                    <div class="col-lg-5 col-md-5 col-sm-5 col-xs-5 pad">
                                        <input type="text" name="remark1" value="" maxlength="40" class="form-control remark1">
                                        <input type="text" name="remark2" value="" maxlength="40" class="form-control remark2">
                                    </div>
                                </div>
        
                                <div class="row">
                                    <div class="col-xs-12 text-right search-action-bar">
                                        <input type="button" class="btn btn-primary savdep" value="SAVE">
                                    </div>
                                </div>
        
                                <input type="text" name="agent" value="<?php echo $accode; ?>" class="form-control agent text-right" style="width:0px" tabindex="-1" readonly>
                            </div>
                            <div class="modal-footer"></div>
                        </div>
                    </div>
                </div>-->

        <?php include("includes/linksfoot.php") ?>

</body>

</html>
<?php
//}
//}



if (isset($_POST["excel"])) {
    $a = 1;

    $compcond = '';

    if (!empty($_POST['company'])) {
        foreach ($_POST['company'] as $check) {
            $mycheck[$count++] .= " OR `company` = '" . $check . "' ";
        }

        foreach ($mycheck as $g => $values) {
            $mcheck .= $values;
        }

        $compcond = " AND (`company` = '' " . $mcheck . " )";
    }
    $mfrmdate = trim($_POST["frmdt"]);
    $mtodate = trim($_POST["todt"]);
    $mname = trim($_POST["acname"]);

    $mfdt = $mfrmdate;
    $mtdt = $mtodate;

    if ($mfrmdate > $mtodate) {
        browse("To Date Cannot Be Less Than From Date");
        header("refresh: 1; ledger_new.php");
        exit();
        $a = 0;
    }

    $maccode = '';
    if ($mname == '') {
        browse("A/c. Name Cannot Be Empty");
        header("refresh: 1; ledger_new.php");
        exit();
        $a = 0;
    } else {
        $maccode = $mname;
    }

    if ($a == 1) {
        $recqry = mysqli_query($conn, " SELECT *, DATE_FORMAT(`date`, '%d-%m-%Y') AS vouchdt  FROM `$accdb`
                                where amount > 0 and source = 'AG' and chqret != 'Y'
                                and date >= '$mfrmdate' and date <= '$mtodate' $compcond     
                                order by date, source, vouchno ") or die(mysqli_error($conn));
        $rcount = mysqli_num_rows($recqry);

        $payqry = mysqli_query($conn, " SELECT *, DATE_FORMAT(`date`, '%d-%m-%Y') AS vouchdt  FROM `$accdb`
                                where amount < 0 and source = 'AG' and chqret != 'Y'
                                and date >= '$mfrmdate' and date <= '$mtodate' $compcond     
                                order by date, source, vouchno ") or die(mysqli_error($conn));
        $lcount = mysqli_num_rows($payqry);

//        $getopen = mysqli_query($conn, "SELECT grpcode, accode, name, openbal, dc  FROM `$maindb` WHERE `accode` = '$maccode' ") or die(mysqli_error($conn));
//
//        $baltmp = mysqli_query($conn, "SELECT * FROM $zroot.`$accbal` WHERE accode = '$maccode' $compcond ") or die(mysqli_error($conn));
//
//        $opb = 0;
//        $opbt = 0;
//        while ($gobal = mysqli_fetch_array($baltmp)) {
//            $opdc = $gobal["dc"];
//
//            if ($opdc == 'D') {
//                $opb = $gobal["openbal"] * -1;
//            } else {
//                $opb = $gobal["openbal"];
//            }
//            $opbt = $opbt + $opb;
//        }
//
//
//        $ctr = 0;
//        $totrecp = 0;
//        $fetopen = mysqli_fetch_array($getopen);
//        $maccode = $fetopen['accode'];
//        $mname = $fetopen['name'];
//
//        $mopen = $opbt;
//
//        $getacc = mysqli_query($conn, "SELECT SUM(amount) AS `openamt` FROM `$accdb` WHERE `accode` = '$maccode' and `date` < '$mfrmdate' and chqret != 'Y' $compcond ") or die(mysqli_error($conn));
//        $fetacc = mysqli_fetch_array($getacc);
//        $openacc = $fetacc['openamt'];
//
//        if ($openacc < 0) {
//            $openacc = $openacc * -1;
//        }
//        $finopen = $mopen + $openacc;
//        $finop = abs($finopen);
//
//        $getacc2 = mysqli_query($conn, "SELECT SUM(amount) AS `openamt` FROM `$accdb` WHERE `accode` = '$maccode' and `date` <= '$mtodate' and chqret != 'Y' $compcond") or die(mysqli_error($conn));
//        $fetacc2 = mysqli_fetch_array($getacc2);
//        $openacc2 = $fetacc2['openamt'];
//
//        $finclos = $mopen + $openacc2;
//        $fincl = abs($finclos);

        require("includes/dbconnect.php");
        mysqli_select_db($conn, $zdb);

        $contents .= "$mname,\n";
        $contents .= "Bills,\n";
        $contents .= "Date,Source,Voucher,Amount\n";

        $lop = 0;
        if ($finopen <= 0) {
            $ctr++;

            $contents .= ",";
            $contents .= ",";
            $contents .= "Opening" . ",";
            $contents .= $finop . "\n";
            $lop = 1;
            $totpay = $totpay + $finop;
        }
        if ($finopen > 0) {

            $contents .= ",";
            $contents .= ",";
            $contents .= ",";
            $contents .= "\n";
        }

        $ctr2 = 0;
        $totpay = 0;
        while ($payment = mysqli_fetch_array($payqry)) {
            $source = $payment['source'];
            $vouchno = $payment['vouchno'];
            $vouchdt = $payment['vouchdt'];
            $payamt = abs($payment['amount']);

            $ctr2++;
            $contents .= $vouchdt . ",";
            $contents .= $source . ",";
            $contents .= $vouchno . ",";
            $contents .= $payamt . "\n";

            $totpay = $totpay + $payamt;
        }

        if ($lcount < $rcount) {
            $ext = $rcount - $lcount;
            for ($i = 0; $i < $ext; $i++) {
                $contents .= ",";
                $contents .= ",";
                $contents .= ",";
                $contents .= "\n";
            }
        }
        $contents .= ",";
        $contents .= ",";
        $contents .= "Total" . ",";
        $contents .= $totpay . "\n";

        if ($finclos > 0) {
            $ctr2++;

            $contents .= ",";
            $contents .= ",";
            $contents .= "Closing" . ",";
            $contents .= "$fincl" . "\n";
        } else {
            $contents .= ",";
            $contents .= ",";
            $contents .= ",";
            $contents .= "\n";
        }






        $contents .= "Receipts\n";
        $contents .= "Date, Source, Voucher, Amount\n";

        if ($finopen > 0) {
            $ctr++;
            $contents .= ",";
            $contents .= ",";
            $contents .= "Opening" . ",";
            $contents .= $finopen . "\n";

            $totrecp = $totrecp + $finopen;
        } else {
            if ($lop == 1) {
                $contents .= ",";
                $contents .= ",";
                $contents .= ",";
                $contents .= "\n";
            }
        }
        $ctr = 0;
        while ($receipt = mysqli_fetch_array($recqry)) {
            $source = $receipt[source];
            $vouchno = $receipt[vouchno];
            $vouchdt = $receipt[vouchdt];
            $recamt = abs($receipt[amount]);

            if ($source == 'BR') {
                $getbank = mysqli_query($conn, "Select date_format(recvdate, '%d-%m-%Y') as recvdate from `bankrecp$ztit` where `vouchno`='$vouchno' $compcond ") or die(mysqli_error($conn));
                $fetbank = mysqli_fetch_array($getbank);
                $vouchdt = $fetbank['recvdate'];
            }
            if ($source == 'CR') {
                $getcash = mysqli_query($conn, "Select date_format(recvdate, '%d-%m-%Y') as recvdate from `cashrecp$ztit` where `vouchno`='$vouchno' $compcond ") or die(mysqli_error($conn));
                $fetcash = mysqli_fetch_array($getcash);
                $vouchdt = $fetcash['recvdate'];
            }


            $ctr++;

            $contents .= $vouchdt . ",";
            $contents .= $source . ",";
            $contents .= $vouchno . ",";
            $contents .= $recamt . "\n";

            $totrecp = $totrecp + $recamt;
        }

        if ($rcount < $lcount) {
            $ext = $lcount - $rcount;
            for ($i = 0; $i < $ext; $i++) {
                $contents .= ",";
                $contents .= ",";
                $contents .= ",";
                $contents .= "\n";
            }
        }
        $contents .= ",";
        $contents .= ",";
        $contents .= "Total" . ",";
        $contents .= $totrecp . "\n";

        if ($finclos <= 0) {
            $ctr2++;
            $contents .= ",";
            $contents .= ",";
            $contents .= "Closing" . ",";
            $contents .= $fincl . "\n";
        } else {
            $contents .= ",";
            $contents .= ",";
            $contents .= ",";
            $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;
    }
}
?>