<?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];
mysqli_select_db($conn, $zdb);

$zyear = $_SESSION["tit_" . $dbname];
//$admin = $_SESSION["admin_" . $dbname];
$maindb = 'accmast';
//browse($_GET["para"]);
$trandb = "actran";
$bankrecp = "bankrecp";
$bankpay = "bankpay";
$cashrecp = "cashrecp";
$cashpay = "cashpay";
$contra = "contra";

$mpara = $_GET["para"];
if ($mpara == "B") {
    $bgrp = "001";
    $msource1 = "BR";
    $msource2 = "BP";
    $dispname = 'Bank';
    $formname = 'Bank Book';
    $grpcode = '001';
} else {
    $bgrp = "002";
    $msource1 = "CR";
    $msource2 = "CP";
    $dispname = 'Cash';
    $formname = 'Cash Book';
    $grpcode = '002';
}


if ($_POST["dtype"] == 1) {
    $repname = $formname . " - Summary";
    $dtype = 1;
} else {
    $repname = $formname . " - Detail";
    $dtype = 2;
}


$mfrmdate = trim($_POST["frmdate"]);
$mtodate = trim($_POST["todt"]);

if ($mfrmdate == "" && $mtodate == "") {
    $mfrmdate = date("Y-m-d");
    $mtodate = date("Y-m-d");
    $_POST["frmdate"] = $mtodate;
    $_POST["todate"] = $mtodate;
}
if (empty($_POST["name"])) {
    $_POST["name"] = "3";
}
if ($_GET["fdt"] != '') {
    $mfrmdate = trim($_GET["fdt"]);
} else {
    $mfrmdate = trim($_POST["frmdate"]);
    if (empty($_POST["frmdate"])) {
        browse("From Date Cannot Be Empty");
        header("refresh:1; bankbook.php");
    }
}
if ($_GET["tdt"] != '') {
    $mtodate = trim($_GET["tdt"]);
} else {
    $mtodate = trim($_POST["todate"]);
    if (empty($_POST["todate"])) {
        browse("To Date Cannot Be Empty");
        header("refresh:1; bankbook.php");
    }
}


$acond = "";
if (!empty($_POST["name"])) {
    $code = $_POST["name"];
    $acond = "AND `accode`='$code'";
} elseif (!empty($_GET["acc"])) {
    $code = $_GET["acc"];
    $acond = "AND `accode`='$code'";
} else {
    if ($dtype == 2) {
        if ($mpara == "B") {
            browse("Bank Name Cannot Be Empty.");
        } else {
            browse("Cash Name Cannot Be Empty.");
        }
        header("refresh: 1; bankbook.php");
        exit();
    }
}




if ($_GET["rpt2"] != '') {
    $prntype = $_GET["rpt2"];
} else {
    $prntype = $_POST["rtype"];
}
$prnnarr = $_POST["prinarr"];

if ($prntype == 1) {
    $repname = $dispname . " Book";
} elseif ($prntype == 2) {
    $repname = $dispname . " Book - Only Debits";
} else {
    $repname = $dispname . " Book - Only Credits";
}
$mfdt = date("d-m-Y", strtotime($mfrmdate));
$mtdt = date("d-m-Y", strtotime($mtodate));

$acc = mysqli_query($conn, "SELECT * FROM `$maindb` WHERE accode !='' $acond") or die(mysqli_error($conn));

if (isset($_POST["submit"]) || ($_GET["view"])) {

    include("includes/linkshead.php");
?>

    <head>
        <style>
            @media print {
                .noPrint {
                    display: none;
                }
            }
        </style>
    </head>

    <body>
        <div class="container">
            <?php include('includes/head_rep.php') ?>
            <div class="row">
                <div class="col-lg-12">
                    <?php if ($dtype == 1) { ?>
                        <table class=" table table-condensed table-bordered table-striped" style="width:60%" border="0">
                        <?php } else {
                        ?>
                            <table class=" table table-condensed table-bordered table-striped" style="width:100%" border="0">
                            <?php }
                            ?>
                            <tbody>
                                <?php
                                mysqli_select_db($conn, $zdb);
                                if ($dtype == 1) {
                                ?>
                                    <tr style="height:10px; " class="mySearchTr">
                                        <th style="text-align:left;width:30%;color: #235410"><b>Bank Name</b></th>
                                        <th style="text-align:right;width:20%;color: #235410"><b>Balance</b></th>
                                    </tr>
                                    <?php
                                    $getbank = mysqli_query($conn, "SELECT accode, name, openbal, dc FROM `accmast` WHERE grpcode = '$grpcode' $acond order by name ") or die(mysqli_error($conn));
                                    while ($bk = mysqli_fetch_array($getbank)) {
                                        $bcode = $bk['accode'];
                                        $bankname = $bk['name'];
                                        $bopen = $bk['openbal'];
                                        $bopdc = $bk['dc'];

                                        $getamt = mysqli_query($conn, "SELECT sum(amount) as bamt FROM `actran` WHERE accode = '$bcode' ") or die(mysqli_error($conn));
                                        $fetamt = mysqli_fetch_array($getamt);
                                        $bamt = $fetamt['bamt'];

                                        if ($bopdc == 'D') {
                                            $bopen = $bopen * -1;
                                        }

                                        $bankbal = $bopen + $bamt;

                                        if ($bankbal <= 0) {
                                            $bdc = 'Dr';
                                        } else {
                                            $bdc = 'Cr';
                                        }
                                        echo "<tr>";
                                        echo "<td>$bankname</td>";
                                        echo "<td class='text-right' style= '$colr'>" . number_format(abs($bankbal), 2) . " " . $bdc . "</td>";
                                        echo "</tr>";
                                        $totbal = $totbal + $bankbal;
                                    }
                                    if ($totbal <= 0) {
                                        $bdctot = 'Dr';
                                    } else {
                                        $bdctot = 'Cr';
                                    }

                                    echo "<tr style='height:10px'>";
                                    echo "<td class='text-right' style='width:35%'><strong>Total</strong></td>";
                                    echo "<td class='text-right'><font color='green'><strong>" . number_format(abs($totbal), 2) . " " . $bdctot . "</strong></font></td>";
                                } else {
                                    $totbal = 0;
                                    while ($getac = mysqli_fetch_array($acc)) {
                                        /** Detail Part* */
                                        $totbal = 0;
                                        $dtot = 0;
                                        $ctot = 0;

                                        $maccode = $getac["accode"];
                                        $mbankinit = $getac["bankinit"];
                                        //                                browse($mbankinit);
                                        $macname = $getac["name"];
                                        $mopbal = $getac["openbal"];
                                        $mopdc = $getac["dc"];

                                        if ($mopdc == "D") {
                                            $mopbal = $mopbal * -1;
                                        }


                                        $ctran1 = mysqli_query($conn, "SELECT *, DATE_FORMAT(`date`, '%d-%m-%Y') as mydt FROM `actran` 
                                                       WHERE accode != '$maccode' and 
                                                       (source = '$msource1' or source = '$msource2') and  
                                                       concat(source,vouchno) in (select concat(source,vouchno) from `actran` 
                                                       where accode = '$maccode' and 
                                                       date >= '$mfrmdate' and date <= '$mtodate' and `retdate` = '0000-00-00'    
                                                       and (source = '$msource1' or source = '$msource2'))  
                                                       union all
                                                       SELECT *, DATE_FORMAT(`date`, '%d-%m-%Y') as mydt FROM `actran` 
                                                       WHERE accode != '$maccode' and source = 'TR' and  
                                                       concat(source,vouchno) in (select concat(source,vouchno) from `actran` 
                                                       where accode = '$maccode'  and `retdate` = '0000-00-00' and
                                                       date >= '$mfrmdate' and date <= '$mtodate' and source = 'TR' )    
                                                       order by date, source, vouchno ") or die(mysqli_error($conn));

                                        //                                print table($ctran1);

                                        $getbal = mysqli_query($conn, "SELECT SUM(amount) as amt FROM `$trandb` WHERE accode = '$maccode' AND 
                                                           `date` < '$mfrmdate' and `retdate` = '0000-00-00' ") or die(mysqli_error($conn));
                                        $getamt = mysqli_fetch_array($getbal);
                                        $amt = $getamt['amt'];

                                        $mobal = $mopbal + $amt;

                                        $mdebit = 0;
                                        $mcredit = 0;

                                        if ($mobal < 0) {
                                            $mdc = "DR";
                                            $mdebit = abs($mobal);
                                            //                                    $dtot = $dtot + $mdebit;
                                        } else {
                                            $mdc = "CR";
                                            $mcredit = abs($mobal);
                                            //                                    $ctot = $ctot + $mcredit;
                                        }

                                        $vdate1 = strtotime($mfrmdate);
                                        $vdate = date('d-m-Y', $vdate1);
                                        $mvouch = "";
                                        $mdescrip = "Opening Balance";
                                        $totbal = $totbal + $mobal;

                                        if ($totbal < 0) {
                                            $mdctot = "DR";
                                            $colr = " color:black";
                                        } else {
                                            $mdctot = "CR";
                                            $colr = " color:red";
                                        }
                                        echo "<tr style='height:10px;background-color: #BABFC2'>";
                                        echo "<th style=\"text-align:left;\" scope=\"col\" width=\"500\" colspan='9'><b>" . strtoupper($macname) . "</b></th>";
                                        echo "</tr>";
                                    ?>
                                        <tr style="height:10px; " class="mySearchTr">
                                            <th style="text-align:left;width:10%"><b>Date</b></th>
                                            <th style="text-align:left;width:10%"><b>Voucher</b></th>
                                            <th style="text-align:left;width:50%" colspan="2"><b>Description</b></th>
                                            <th style="text-align:right;width:10%"><b>Debit</b></th>
                                            <th style="text-align:right;width:10%"><b>Credit</b></th>
                                            <th style="text-align:right;width:10%"><b>Balance</b></th>
                                        </tr>

                                <?php
                                        echo "<td>$vdate</td>";
                                        echo "<td>$mvouch</td>";
                                        echo "<td colspan='2'>$mdescrip</td>";

                                        if ($prntype == 1) {
                                            echo "<td class='text-right'>" . number_format($mdebit, 2) . "</td>";
                                            echo "<td class='text-right'>" . number_format($mcredit, 2) . "</td>";

                                            echo "<td class='text-right' style= '$colr'>" . number_format(abs($totbal), 2) . " " . $mdctot . "</td>";
                                        } elseif ($prntype == 2) {
                                            echo "<td class='text-right'>" . number_format($mdebit, 2) . "</td>";
                                            echo "<td></td>";
                                            echo "<td></td>";
                                        } else {
                                            echo "<td></td>";
                                            echo "<td class='text-right'>" . number_format($mcredit, 2) . "</td>";
                                            echo "<td></td>";
                                        }

                                        if ($mcredit > 0) {
                                            $opening = round($mcredit);
                                        } else {
                                            $opening = round($mdebit);
                                        }
                                        while ($row = mysqli_fetch_assoc($ctran1)) {

                                            $vdate = $row["mydt"];
                                            $msource = $row["source"];
                                            $mvouch = $row["vouchno"];
                                            $mamount = $row["amount"];
                                            $daccode = $row["accode"];
                                            $mdebit = 0;
                                            $mcredit = 0;

                                            if ($mamount > 0) {
                                                $mdc = "DR";
                                                $mdebit = abs($mamount);
                                                $dtot = $dtot + $mdebit;
                                                $totbal = $totbal - abs($mamount);
                                            } else {
                                                $mdc = "CR";
                                                $mcredit = abs($mamount);
                                                $ctot = $ctot + $mcredit;
                                                $totbal = $totbal + abs($mamount);
                                            }

                                            if ($totbal < 0) {
                                                $mdctot = "DR";
                                                $colr = " color:black";
                                            } else {
                                                $mdctot = "CR";
                                                $colr = " color:red";
                                            }
                                            $mdescrip = "";
                                            $mchqdtl = "";
                                            $mnarr = "";

                                            $nqry1 = mysqli_query($conn, "SELECT name FROM `accmast` WHERE accode = '$daccode'") or die(mysqli_error($conn));
                                            $nqry = mysqli_fetch_array($nqry1);

                                            $head = $nqry["name"];

                                            switch ($msource) {

                                                case "BR";
                                                    if ($prnnarr == 1) {
                                                        $nqry1 = mysqli_query($conn, "SELECT chqno, DATE_FORMAT(`chqdate`, '%d-%m-%Y') as mbilldate, remark1
                                                                        FROM `$bankrecp`
                                                                       WHERE vouchno='$mvouch'") or die(mysqli_error($conn));
                                                        $nqry = mysqli_fetch_array($nqry1);

                                                        $mbill = $nqry["chqno"];
                                                        $mbilldt = $nqry["mbilldate"];
                                                        $mnarr = $nqry["remark1"];
                                                        // Browse($mnarr . 'BR');

                                                        $mchqdtl = "Cheque No. : " . trim($mbill) . " &nbsp;&nbsp;Dated : " . $mbilldt;
                                                    }
                                                    break;

                                                case "BP";

                                                    if ($prnnarr == 1) {
                                                        $nqry1 = mysqli_query($conn, "SELECT chqno, DATE_FORMAT(`chqdate`, '%d-%m-%Y') as mbilldate, remark1 
                                                                         FROM `$bankpay`
                                                                       WHERE vouchno='$mvouch'") or die(mysqli_error($conn));
                                                        $nqry = mysqli_fetch_array($nqry1);

                                                        $mbill = $nqry["chqno"];
                                                        $mbilldt = $nqry["mbilldate"];
                                                        $mnarr = $nqry["remark1"];
                                                        // Browse($mnarr . 'BP');
                                                        $mchqdtl = "Cheque No. : " . trim($mbill) . " &nbsp;&nbsp;Dated : " . $mbilldt;
                                                    }
                                                    break;

                                                case "CR";

                                                    if ($prnnarr == 1) {
                                                        $nqry1 = mysqli_query($conn, "SELECT `remark1`, remark2 FROM `$cashrecp`
                                                                       WHERE vouchno='$mvouch'") or die(mysqli_error($conn));
                                                        $nqry = mysqli_fetch_array($nqry1);

                                                        $mbill = '';
                                                        $mbilldt = '';
                                                        $mnarr = $nqry["remark1"] . ' ' . $nqry["remark2"];
                                                        // Browse($mnarr . 'CR');
                                                        //$mchqdtl = "Cheque No. : ".+ trim($mbill)." &nbsp;&nbsp;Dated : ".$mbilldt;  
                                                    }
                                                    break;

                                                case "CP";

                                                    if ($prnnarr == 1) {
                                                        $nqry1 = mysqli_query($conn, "SELECT `remark1` FROM `$cashpay`
                                                                       WHERE vouchno='$mvouch'") or die(mysqli_error($conn));
                                                        $nqry = mysqli_fetch_array($nqry1);

                                                        $mbill = $nqry[""];
                                                        $mbilldt = $nqry[""];
                                                        $mnarr = $nqry["remark1"];
                                                        // Browse($mnarr . 'CP');
                                                        //$mchqdtl = "Cheque No. : ".+ trim($mbill)." &nbsp;&nbsp;Dated : ".$mbilldt;  
                                                    }
                                                    break;

                                                case "TR";
                                                    //                                            $head = "Contra / Transfer";
                                                    if ($mamount > 0) {
                                                        $head = "To " . $head;
                                                    } else {
                                                        $head = "From " . $head;
                                                    }
                                                    if ($prnnarr == 1) {
                                                        $nqry1 = mysqli_query($conn, "SELECT chqno, DATE_FORMAT(`chqdate`, '%d-%m-%Y') as mbilldate, narr1, narr2
                                                                        FROM `$contra` WHERE vouchno='$mvouch'") or die(mysqli_error($conn));
                                                        $nqry = mysqli_fetch_array($nqry1);

                                                        $mbill = $nqry["chqno"];
                                                        $mbilldt = $nqry["mbilldate"];

                                                        $mnarr = trim($nqry["narr1"]) . ' ' . trim($nqry["narr2"]);
                                                        if ($mbill != '') {
                                                            $mchqdtl = "Cheque No. : " . trim($mbill) . " &nbsp;&nbsp;Dated : " . $mbilldt;
                                                        } else {
                                                            $mchqdtl = '';
                                                        }
                                                    }
                                                    break;
                                                default:
                                                    $head = "Other";
                                            }
                                            echo "<tr style='height:10px;background-color:white'>";
                                            echo "<td>$vdate</td>";
                                            echo "<td>" . $msource . " " . $mvouch . "</td>";
                                            echo "<td  colspan='2'>$head";

                                            if ($prnnarr == 1) {
                                                if (!empty($mchqdtl)) {
                                                    echo "<br/>$mchqdtl";
                                                }
                                                if (!empty($mnarr)) {
                                                    echo "<br/>";
                                                    echo $mnarr;
                                                }
                                                echo "</td>";
                                            }
                                            echo "</td>";
                                            if ($prntype == 1) {
                                                echo "<td class='text-right'>" . number_format($mdebit, 2) . "</td>";
                                                echo "<td class='text-right'>" . number_format($mcredit, 2) . "</td>";
                                                echo "<td class='text-right' style='$colr'>" . number_format(abs($totbal), 2) . " " . $mdctot . "</td>";
                                            } elseif ($prntype == 2) {
                                                echo "<td class='text-right'>" . number_format($mdebit, 2) . "</td>";

                                                echo "<td ></td>";
                                                echo "<td ></td>";
                                            } else {

                                                echo "<td ></td>";
                                                echo "<td class='text-right'>" . number_format($mcredit, 2) . "</td>";
                                                echo "<td ></td>";
                                            }
                                            echo "</tr>";
                                        }

                                        if ($mobal < 0) {
                                            $dtot = $dtot + $opening;
                                        } else {
                                            $ctot = $ctot + $opening;
                                        }

                                        echo "<tr style='height:10px'>";
                                        echo "<td ></td>";
                                        echo "<td ></td>";
                                        echo "<td ></td>";
                                        echo "<td class='text-right' style='width:35%'><strong>Total</strong></td>";
                                        //                                echo "<td class='text-right' style='width:15%'><strong>Opening - $opening</strong></td>";

                                        if ($prntype == 1) {
                                            echo "<td class='text-right'>" . number_format(abs($dtot), 2) . "</td>";
                                            echo "<td class='text-right'>" . number_format(abs($ctot), 2) . "</td>";

                                            if ($totbal < 0) {
                                                $atotbal = abs($totbal);
                                                echo "<td class='text-right'><font color='green'><strong>" . number_format($atotbal, 2) . " " . $mdctot . "</strong></font></td>";
                                            } else {
                                                echo "<td class='text-right'><font color='red'><strong> -" . number_format(abs($totbal), 2) . " " . $mdctot . "</strong></font></td>";
                                            }
                                        } elseif ($prntype == 2) {
                                            echo "<td class='text-right'>" . number_format($dtot, 2) . "</td>";
                                            echo "<td ></td>";
                                        } else {

                                            echo "<td ></td>";
                                            echo "<td class='text-right'>" . number_format($ctot, 2) . "</td>";
                                        }
                                        echo "</tr>";
                                    }
                                }
                                ?>
                            </tbody>
                            </table>
                </div>
            </div>
        </div>
    <?php
    include("includes/linksfoot.php");
}

if (isset($_POST["excel"]) || ($_GET["excel"])) {
    $contents = "";
    mysqli_select_db($conn, $zdb);
    if ($dtype == 1) {


        $contents .= "Bank Name, Balance \n";

        $getbank = mysqli_query($conn, "SELECT accode, name, openbal, dc FROM `accmast` WHERE grpcode = '$grpcode' $acond order by name ") or die(mysqli_error($conn));
        while ($bk = mysqli_fetch_array($getbank)) {
            $bcode = $bk['accode'];
            $bankname = $bk['name'];
            $bopen = $bk['openbal'];
            $bopdc = $bk['dc'];

            $getamt = mysqli_query($conn, "SELECT sum(amount) as bamt FROM `actran` WHERE accode = '$bcode' ") or die(mysqli_error($conn));
            $fetamt = mysqli_fetch_array($getamt);
            $bamt = $fetamt['bamt'];

            if ($bopdc == 'D') {
                $bopen = $bopen * -1;
            }

            $bankbal = $bopen + $bamt;

            if ($bankbal <= 0) {
                $bdc = 'Dr';
            } else {
                $bdc = 'Cr';
            }

            $contents .= "$bankname" . ",";
            $contents .= "$bankbal $bdc" . "\n";
            $totbal = $totbal + $bankbal;
        }
        if ($totbal <= 0) {
            $bdctot = 'Dr';
        } else {
            $bdctot = 'Cr';
        }

        $contents .= "Total" . ",";
        $contents .= "$totbal $bdctot" . ",";
    } else {
        $totbal = 0;
        while ($getac = mysqli_fetch_array($acc)) {
            /** Detail Part* */
            $totbal = 0;
            $dtot = 0;
            $ctot = 0;

            $maccode = $getac["accode"];
            $mbankinit = $getac["bankinit"];
            //                                browse($mbankinit);
            $macname = $getac["name"];
            $mopbal = $getac["openbal"];
            $mopdc = $getac["dc"];

            if ($mopdc == "D") {
                $mopbal = $mopbal * -1;
            }


            $ctran1 = mysqli_query($conn, "SELECT *, DATE_FORMAT(`date`, '%d-%m-%Y') as mydt FROM `actran` 
                                                       WHERE accode != '$maccode' and 
                                                       (source = '$msource1' or source = '$msource2') and  
                                                       concat(source,vouchno) in (select concat(source,vouchno) from `actran` 
                                                       where accode = '$maccode' and 
                                                       date >= '$mfrmdate' and date <= '$mtodate' and `retdate` = '0000-00-00'    
                                                       and (source = '$msource1' or source = '$msource2'))  
                                                       union all
                                                       SELECT *, DATE_FORMAT(`date`, '%d-%m-%Y') as mydt FROM `actran` 
                                                       WHERE accode != '$maccode' and source = 'TR' and  
                                                       concat(source,vouchno) in (select concat(source,vouchno) from `actran` 
                                                       where accode = '$maccode'  and `retdate` = '0000-00-00' and
                                                       date >= '$mfrmdate' and date <= '$mtodate' and source = 'TR' )    
                                                       order by date, source, vouchno ") or die(mysqli_error($conn));

            //                                print table($ctran1);

            $getbal = mysqli_query($conn, "SELECT SUM(amount) as amt FROM `$trandb` WHERE accode = '$maccode' AND 
                                                           `date` < '$mfrmdate' and `retdate` = '0000-00-00' ") or die(mysqli_error($conn));
            $getamt = mysqli_fetch_array($getbal);
            $amt = $getamt['amt'];

            $mobal = $mopbal + $amt;

            $mdebit = 0;
            $mcredit = 0;

            if ($mobal < 0) {
                $mdc = "DR";
                $mdebit = abs($mobal);
                //                                    $dtot = $dtot + $mdebit;
            } else {
                $mdc = "CR";
                $mcredit = abs($mobal);
                //                                    $ctot = $ctot + $mcredit;
            }

            $vdate1 = strtotime($mfrmdate);
            $vdate = date('d-m-Y', $vdate1);
            $mvouch = "";
            $mdescrip = "Opening Balance";
            $totbal = $totbal + $mobal;

            if ($totbal < 0) {
                $mdctot = "DR";
                $colr = " color:black";
            } else {
                $mdctot = "CR";
                $colr = " color:red";
            }
            $partyname = strtoupper($macname);
            $contents .= "$partyname \n";

            $contents .= "Date, Voucher, Description, Debit, Credit, Balance \n";

            $contents .= "$vdate" . ",";
            $contents .= "$mvouch" . ",";
            $contents .= "$mdescrip" . ",";

            if ($prntype == 1) {
                $contents .= "$mdebit" . ",";
                $contents .= "$mcredit" . ",";
                $contents .= "$totbal $mdctot" . ",";
            } elseif ($prntype == 2) {
                $contents .= "$mdebit" . ",,,";
            } else {
                $contents .= "" . ",";
                $contents .= "$mcredit" . ",,";
            }

            $contents .= "" . "\n";
            if ($mcredit > 0) {
                $opening = round($mcredit);
            } else {
                $opening = round($mdebit);
            }
            while ($row = mysqli_fetch_assoc($ctran1)) {

                $vdate = $row["mydt"];
                $msource = $row["source"];
                $mvouch = $row["vouchno"];
                $mamount = $row["amount"];
                $daccode = $row["accode"];
                $mdebit = 0;
                $mcredit = 0;

                if ($mamount > 0) {
                    $mdc = "DR";
                    $mdebit = abs($mamount);
                    $dtot = $dtot + $mdebit;
                    $totbal = $totbal - abs($mamount);
                } else {
                    $mdc = "CR";
                    $mcredit = abs($mamount);
                    $ctot = $ctot + $mcredit;
                    $totbal = $totbal + abs($mamount);
                }

                if ($totbal < 0) {
                    $mdctot = "DR";
                    $colr = " color:black";
                } else {
                    $mdctot = "CR";
                    $colr = " color:red";
                }
                $mdescrip = "";
                $mchqdtl = "";
                $mnarr = "";

                $nqry1 = mysqli_query($conn, "SELECT name FROM `accmast` WHERE accode = '$daccode'") or die(mysqli_error($conn));
                $nqry = mysqli_fetch_array($nqry1);

                $head = $nqry["name"];

                switch ($msource) {

                    case "BR";
                        if ($prnnarr == 1) {
                            $nqry1 = mysqli_query($conn, "SELECT chqno, DATE_FORMAT(`chqdate`, '%d-%m-%Y') as mbilldate, remark1
                                                                        FROM `$bankrecp`
                                                                       WHERE vouchno='$mvouch'") or die(mysqli_error($conn));
                            $nqry = mysqli_fetch_array($nqry1);

                            $mbill = $nqry["chqno"];
                            $mbilldt = $nqry["mbilldate"];
                            $mnarr = $nqry["remark1"];
                            // Browse($mnarr . 'BR');

                            $mchqdtl = "Cheque No. : " . trim($mbill) . " &nbsp;&nbsp;Dated : " . $mbilldt;
                        }
                        break;

                    case "BP";

                        if ($prnnarr == 1) {
                            $nqry1 = mysqli_query($conn, "SELECT chqno, DATE_FORMAT(`chqdate`, '%d-%m-%Y') as mbilldate, remark1 
                                                                         FROM `$bankpay`
                                                                       WHERE vouchno='$mvouch'") or die(mysqli_error($conn));
                            $nqry = mysqli_fetch_array($nqry1);

                            $mbill = $nqry["chqno"];
                            $mbilldt = $nqry["mbilldate"];
                            $mnarr = $nqry["remark1"];
                            // Browse($mnarr . 'BP');
                            $mchqdtl = "Cheque No. : " . trim($mbill) . " &nbsp;&nbsp;Dated : " . $mbilldt;
                        }
                        break;

                    case "CR";

                        if ($prnnarr == 1) {
                            $nqry1 = mysqli_query($conn, "SELECT `remark1`, remark2 FROM `$cashrecp`
                                                                       WHERE vouchno='$mvouch'") or die(mysqli_error($conn));
                            $nqry = mysqli_fetch_array($nqry1);

                            $mbill = '';
                            $mbilldt = '';
                            $mnarr = $nqry["remark1"] . ' ' . $nqry["remark2"];
                            // Browse($mnarr . 'CR');
                            //$mchqdtl = "Cheque No. : ".+ trim($mbill)." &nbsp;&nbsp;Dated : ".$mbilldt;  
                        }
                        break;

                    case "CP";

                        if ($prnnarr == 1) {
                            $nqry1 = mysqli_query($conn, "SELECT `remark1` FROM `$cashpay`
                                                                       WHERE vouchno='$mvouch'") or die(mysqli_error($conn));
                            $nqry = mysqli_fetch_array($nqry1);

                            $mbill = $nqry[""];
                            $mbilldt = $nqry[""];
                            $mnarr = $nqry["remark1"];
                            // Browse($mnarr . 'CP');
                            //$mchqdtl = "Cheque No. : ".+ trim($mbill)." &nbsp;&nbsp;Dated : ".$mbilldt;  
                        }
                        break;

                    case "TR";
                        //                                            $head = "Contra / Transfer";
                        if ($mamount > 0) {
                            $head = "To " . $head;
                        } else {
                            $head = "From " . $head;
                        }
                        if ($prnnarr == 1) {
                            $nqry1 = mysqli_query($conn, "SELECT chqno, DATE_FORMAT(`chqdate`, '%d-%m-%Y') as mbilldate, narr1, narr2
                                                                        FROM `$contra` WHERE vouchno='$mvouch'") or die(mysqli_error($conn));
                            $nqry = mysqli_fetch_array($nqry1);

                            $mbill = $nqry["chqno"];
                            $mbilldt = $nqry["mbilldate"];

                            $mnarr = trim($nqry["narr1"]) . ' ' . trim($nqry["narr2"]);
                            if ($mbill != '') {
                                $mchqdtl = "Cheque No. : " . trim($mbill) . " &nbsp;&nbsp;Dated : " . $mbilldt;
                            } else {
                                $mchqdtl = '';
                            }
                        }
                        break;
                    default:
                        $head = "Other";
                }

                $contents .= "$vdate" . ",";
                $contents .= "$msource $mvouch" . ",";
                $contents .= "$head" . ",";

                if ($prntype == 1) {
                    $contents .= "$mdebit" . ",";
                    $contents .= "$mcredit" . ",";
                    $contents .= "$totbal $mdctot" . ",";
                } elseif ($prntype == 2) {
                    $contents .= "$mdebit" . ",,,";
                } else {
                    $contents .= "" . ",";
                    $contents .= "$mcredit" . ",,";
                }
                $contents .= "\n";
                if ($prnnarr == 1) {
                    if (!empty($mchqdtl)) {
                        $contents .= "" . ",,";
                        $contents .= "$mchqdtl" . "\n";
                    }
                    if (!empty($mnarr)) {
                        $contents .= "" . ",,";
                        $contents .= "$mnarr" . "\n";
                    }
                }
            }

            if ($mobal < 0) {
                $dtot = $dtot + $opening;
            } else {
                $ctot = $ctot + $opening;
            }

            $contents .= "" . ",,";
            $contents .= "Total" . ",";
            if ($prntype == 1) {
                $contents .= "$dtot" . ",";
                $contents .= "$ctot" . ",";
                if ($totbal < 0) {
                    $atotbal = abs($totbal);
                    $contents .= "$atotbal $mdctot" . ",";
                } else {
                    $contents .= "$totbal $mdctot" . ",";
                }
            } elseif ($prntype == 2) {
                $contents .= "$dtot" . ",,";
            } else {

                $contents .= "" . ",";
                $contents .= "$ctot" . ",";
                $contents .= "" . ",";
                $contents .= "$ctot" . ",";
            }
            $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;
    }
}


// LEDGER PDF

if (isset($_POST["subpdf"]) || isset($_POST["whatspdf"])) {

    ini_set('display_errors', 1);
    error_reporting(E_ERROR);

    require("library/fpdf/fpdf.php");

    class pdf extends fpdf
    {
        function Footer()
        {
            $this->SetY(-15);
            $this->SetFont('Arial', 'I', 8);
            $this->Cell(0, 10, 'Page ' . $this->PageNo() . '/{nb}', 0, 0, 'C');
        }
    }

    $ln = 0;
    $pagerow = 25;
    $pdf = new pdf('P', 'mm', 'A4');
    $pdf->AliasNbPages();
    $pdf->AddPage();


    $zroot = $_SESSION["zdir"];
    $zcomp = $_SESSION["comp_" . $dbname];
    $getcomp = mysqli_query($conn, "SELECT * FROM $zroot.`company` WHERE `code`= '$zcomp' ") or die(mysqli_error($conn));
    $comp = mysqli_fetch_array($getcomp);

    $pdf->SetFont('Arial', 'B', 12);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->SetFillColor(152, 249, 240);

    $addy = $_REQUEST["dtype"];
    // $mfdt = $_REQUEST["frmdt"];
    // $mtdt = $_REQUEST["todt"];

    if ($dtype == 1) {
        $rtype = "Summary";
    } elseif ($dtype == 2) {
        $rtype = "Detail";
    } elseif ($dtype == '0') {
        $rtype = 'Monthly Summary';
    }

    $pdf->Cell(190, 6, strtoupper($comp['compname']), 'LRT', 0, 'L', 1);
    $pdf->Ln();
    $pdf->SetFont('Arial', 'B', 9);
    $pdf->Cell(190, 6, $comp['hoadd1'] . $comp['hoadd2'] . $comp['hoadd3'], 'LR', 0, '', 1);
    $pdf->Ln();
    $pdf->SetTextColor(255, 0, 0);
    $pdf->Cell(120, 6, "$formname - " . $rtype, 'L', 0, '', 1);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->Cell(70, 6, "Report Date-" . Date("d-m-Y"), 'R', 0, 'R', 1);
    $pdf->Ln();
    $pdf->Cell(190, 6, 'From Date - ' . $mfdt . "     To Date - " . $mtdt, 'LRB', 0, '', 1);
    $pdf->Ln();

    mysqli_select_db($conn, $zdb);

    if ($dtype == 1) {
        $ht = 7;
        $pdf->SetFont('Arial', 'B', 9);
        $pdf->SetFillColor(255, 255, 255);


        $pdf->SetTextColor(35, 84, 16);
        $pdf->Cell(100, $ht, 'Bank Name', 1, 0, '', 1);
        $pdf->Cell(40, $ht, 'Balance', 1, 0, 'R', 1);
        $pdf->ln($ht);

        $pdf->SetTextColor(0, 0, 0);

        $getbank = mysqli_query($conn, "SELECT accode, name, openbal, dc FROM `accmast` WHERE grpcode = '$grpcode' $acond order by name ") or die(mysqli_error($conn));
        while ($bk = mysqli_fetch_array($getbank)) {
            $bcode = $bk['accode'];
            $bankname = $bk['name'];
            $bopen = $bk['openbal'];
            $bopdc = $bk['dc'];

            $getamt = mysqli_query($conn, "SELECT sum(amount) as bamt FROM `actran` WHERE accode = '$bcode' ") or die(mysqli_error($conn));
            $fetamt = mysqli_fetch_array($getamt);
            $bamt = $fetamt['bamt'];

            if ($bopdc == 'D') {
                $bopen = $bopen * -1;
            }

            $bankbal = $bopen + $bamt;

            if ($bankbal <= 0) {
                $bdc = 'Dr';
            } else {
                $bdc = 'Cr';
            }


            $pdf->Cell(100, $ht, $bankname, 1, 0, '', 1);
            $pdf->Cell(40, $ht, number_format(abs($bankbal), 2) . " " . $bdc, 1, 0, 'R', 1);
            $pdf->ln($ht);

            $totbal = $totbal + $bankbal;
        }
        if ($totbal <= 0) {
            $bdctot = 'Dr';
        } else {
            $bdctot = 'Cr';
        }

        $pdf->Cell(100, $ht, "Total", 1, 0, 'R', 1);

        $pdf->SetTextColor(35, 84, 16);
        $pdf->Cell(40, $ht, number_format(abs($totbal), 2) . " " . $bdctot, 1, 0, 'R', 1);
        $pdf->ln($ht);

        $pdf->SetTextColor(0, 0, 0);
    } else {



        $dateW = 20;
        $vouchW = 22;
        $descW = 78;
        $debitW = 22;
        $creditW = 22;
        $balW = 26;

        $pdf->SetFont('Arial', 'B', 10);
        $pdf->SetFillColor(186, 191, 194);
        $pdf->SetTextColor(0, 0, 0);

        $totbal = 0;
        while ($getac = mysqli_fetch_array($acc)) {
            /** Detail Part* */
            $totbal = 0;
            $dtot = 0;
            $ctot = 0;

            $maccode = $getac["accode"];
            $mbankinit = $getac["bankinit"];
            //                                browse($mbankinit);
            $macname = $getac["name"];
            $mopbal = $getac["openbal"];
            $mopdc = $getac["dc"];

            if ($mopdc == "D") {
                $mopbal = $mopbal * -1;
            }


            $ctran1 = mysqli_query($conn, "SELECT *, DATE_FORMAT(`date`, '%d-%m-%Y') as mydt FROM `actran` 
                                                       WHERE accode != '$maccode' and 
                                                       (source = '$msource1' or source = '$msource2') and  
                                                       concat(source,vouchno) in (select concat(source,vouchno) from `actran` 
                                                       where accode = '$maccode' and 
                                                       date >= '$mfrmdate' and date <= '$mtodate' and `retdate` = '0000-00-00'    
                                                       and (source = '$msource1' or source = '$msource2'))  
                                                       union all
                                                       SELECT *, DATE_FORMAT(`date`, '%d-%m-%Y') as mydt FROM `actran` 
                                                       WHERE accode != '$maccode' and source = 'TR' and  
                                                       concat(source,vouchno) in (select concat(source,vouchno) from `actran` 
                                                       where accode = '$maccode'  and `retdate` = '0000-00-00' and
                                                       date >= '$mfrmdate' and date <= '$mtodate' and source = 'TR' )    
                                                       order by date, source, vouchno ") or die(mysqli_error($conn));

            //                                print table($ctran1);

            $getbal = mysqli_query($conn, "SELECT SUM(amount) as amt FROM `$trandb` WHERE accode = '$maccode' AND 
                                                           `date` < '$mfrmdate' and `retdate` = '0000-00-00' ") or die(mysqli_error($conn));
            $getamt = mysqli_fetch_array($getbal);
            $amt = $getamt['amt'];

            $mobal = $mopbal + $amt;

            $mdebit = 0;
            $mcredit = 0;

            if ($mobal < 0) {
                $mdc = "DR";
                $mdebit = abs($mobal);
            } else {
                $mdc = "CR";
                $mcredit = abs($mobal);
            }

            $vdate1 = strtotime($mfrmdate);
            $vdate = date('d-m-Y', $vdate1);
            $mvouch = "";
            $mdescrip = "Opening Balance";
            $totbal = $totbal + $mobal;

            if ($totbal < 0) {
                $mdctot = "DR";
                $colr = " color:black";
            } else {
                $mdctot = "CR";
                $colr = " color:red";
            }

            if ($pdf->GetY() > 250) {
                $pdf->AddPage();
            }

            $pdf->Ln(2);

            $pdf->SetFont('Arial', 'B', 10);
            $pdf->SetFillColor(186, 191, 194);

            $pdf->Cell(
                $dateW + $vouchW + $descW + $debitW + $creditW + $balW,
                7,
                strtoupper($macname),
                1,
                1,
                'L',
                true
            );

            $pdf->SetFont('Arial', 'B', 8);

            $pdf->SetFillColor(72, 146, 255);
            $pdf->SetTextColor(255, 255, 255);


            $pdf->Cell($dateW, 6, 'Date', 1, 0, 'L', true);
            $pdf->Cell($vouchW, 6, 'Voucher', 1, 0, 'L', true);
            $pdf->Cell($descW, 6, 'Description', 1, 0, 'L', true);
            $pdf->Cell($debitW, 6, 'Debit', 1, 0, 'R', true);
            $pdf->Cell($creditW, 6, 'Credit', 1, 0, 'R', true);
            $pdf->Cell($balW, 6, 'Balance', 1, 1, 'R', true);


            $pdf->SetTextColor(0, 0, 0);
            $pdf->SetFont('Arial', '', 8);

            $baltxt = number_format(abs($totbal), 2) . " " . $mdctot;

            $pdf->Cell($dateW, 6, $vdate, 1);
            $pdf->Cell($vouchW, 6, '', 1);
            $pdf->Cell($descW, 6, 'Opening Balance', 1);

            $pdf->Cell(
                $debitW,
                6,
                $mdebit > 0 ? number_format($mdebit, 2) : '',
                1,
                0,
                'R'
            );

            $pdf->Cell(
                $creditW,
                6,
                $mcredit > 0 ? number_format($mcredit, 2) : '',
                1,
                0,
                'R'
            );

            $pdf->Cell($balW, 6, $baltxt, 1, 1, 'R');

            if ($mcredit > 0) {
                $opening = round($mcredit);
            } else {
                $opening = round($mdebit);
            }

            while ($row = mysqli_fetch_assoc($ctran1)) {

                $vdate = $row["mydt"];
                $msource = $row["source"];
                $mvouch = $row["vouchno"];
                $mamount = $row["amount"];
                $daccode = $row["accode"];
                $mdebit = 0;
                $mcredit = 0;

                if ($mamount > 0) {
                    $mdc = "DR";
                    $mdebit = abs($mamount);
                    $dtot = $dtot + $mdebit;
                    $totbal = $totbal - abs($mamount);
                } else {
                    $mdc = "CR";
                    $mcredit = abs($mamount);
                    $ctot = $ctot + $mcredit;
                    $totbal = $totbal + abs($mamount);
                }

                if ($totbal < 0) {
                    $mdctot = "DR";
                    $colr = " color:black";
                } else {
                    $mdctot = "CR";
                    $colr = " color:red";
                }
                $mdescrip = "";
                $mchqdtl = "";
                $mnarr = "";

                $nqry1 = mysqli_query($conn, "SELECT name FROM `accmast` WHERE accode = '$daccode'") or die(mysqli_error($conn));
                $nqry = mysqli_fetch_array($nqry1);

                $head = $nqry["name"];

                switch ($msource) {

                    case "BR":
                        if ($prnnarr == 1) {
                            $nqry1 = mysqli_query($conn, "SELECT chqno, DATE_FORMAT(`chqdate`, '%d-%m-%Y') as mbilldate, remark1
                                                                        FROM `$bankrecp`
                                                                       WHERE vouchno='$mvouch'") or die(mysqli_error($conn));
                            $nqry = mysqli_fetch_array($nqry1);

                            $mbill = $nqry["chqno"];
                            $mbilldt = $nqry["mbilldate"];
                            $mnarr = $nqry["remark1"];
                            // Browse($mnarr . 'BR');

                            $mchqdtl = "Cheque No. : " . trim($mbill) . " &nbsp;&nbsp;Dated : " . $mbilldt;
                        }
                        break;

                    case "BP":

                        if ($prnnarr == 1) {
                            $nqry1 = mysqli_query($conn, "SELECT chqno, DATE_FORMAT(`chqdate`, '%d-%m-%Y') as mbilldate, remark1 
                                                                         FROM `$bankpay`
                                                                       WHERE vouchno='$mvouch'") or die(mysqli_error($conn));
                            $nqry = mysqli_fetch_array($nqry1);

                            $mbill = $nqry["chqno"];
                            $mbilldt = $nqry["mbilldate"];
                            $mnarr = $nqry["remark1"];
                            // Browse($mnarr . 'BP');
                            $mchqdtl = "Cheque No. : " . trim($mbill) . " &nbsp;&nbsp;Dated : " . $mbilldt;
                        }
                        break;

                    case "CR":

                        if ($prnnarr == 1) {
                            $nqry1 = mysqli_query($conn, "SELECT `remark1`, remark2 FROM `$cashrecp`
                                                                       WHERE vouchno='$mvouch'") or die(mysqli_error($conn));
                            $nqry = mysqli_fetch_array($nqry1);

                            $mbill = '';
                            $mbilldt = '';
                            $mnarr = $nqry["remark1"] . ' ' . $nqry["remark2"];
                            // Browse($mnarr . 'CR');
                            //$mchqdtl = "Cheque No. : ".+ trim($mbill)." &nbsp;&nbsp;Dated : ".$mbilldt;  
                        }
                        break;

                    case "CP":

                        if ($prnnarr == 1) {
                            $nqry1 = mysqli_query($conn, "SELECT `remark1` FROM `$cashpay`
                                                                       WHERE vouchno='$mvouch'") or die(mysqli_error($conn));
                            $nqry = mysqli_fetch_array($nqry1);

                            $mbill = $nqry[""];
                            $mbilldt = $nqry[""];
                            $mnarr = $nqry["remark1"];
                            // Browse($mnarr . 'CP');
                            //$mchqdtl = "Cheque No. : ".+ trim($mbill)." &nbsp;&nbsp;Dated : ".$mbilldt;  
                        }
                        break;

                    case "TR":
                        //                                            $head = "Contra / Transfer";
                        if ($mamount > 0) {
                            $head = "To " . $head;
                        } else {
                            $head = "From " . $head;
                        }
                        if ($prnnarr == 1) {
                            $nqry1 = mysqli_query($conn, "SELECT chqno, DATE_FORMAT(`chqdate`, '%d-%m-%Y') as mbilldate, narr1, narr2
                                                                        FROM `$contra` WHERE vouchno='$mvouch'") or die(mysqli_error($conn));
                            $nqry = mysqli_fetch_array($nqry1);

                            $mbill = $nqry["chqno"];
                            $mbilldt = $nqry["mbilldate"];

                            $mnarr = trim($nqry["narr1"]) . ' ' . trim($nqry["narr2"]);
                            if ($mbill != '') {
                                $mchqdtl = "Cheque No. : " . trim($mbill) . " &nbsp;&nbsp;Dated : " . $mbilldt;
                            } else {
                                $mchqdtl = '';
                            }
                        }
                        break;

                    default:
                        $head = "Other";
                }

                $desc = $head;

                if ($prnnarr == 1) {

                    if (!empty($mchqdtl)) {
                        $desc .= " | " . $mchqdtl;
                    }

                    if (!empty($mnarr)) {
                        $desc .= " | " . $mnarr;
                    }
                }

                $baltxt = number_format(abs($totbal), 2) . " " . $mdctot;

                $pdf->Cell($dateW, 6, $vdate, 1);

                $pdf->Cell(
                    $vouchW,
                    6,
                    $msource . ' ' . $mvouch,
                    1
                );

                $pdf->Cell(
                    $descW,
                    6,
                    substr($desc, 0, 55),
                    1
                );

                $pdf->Cell(
                    $debitW,
                    6,
                    $mdebit > 0 ? number_format($mdebit, 2) : '',
                    1,
                    0,
                    'R'
                );

                $pdf->Cell(
                    $creditW,
                    6,
                    $mcredit > 0 ? number_format($mcredit, 2) : '',
                    1,
                    0,
                    'R'
                );

                $pdf->Cell(
                    $balW,
                    6,
                    $baltxt,
                    1,
                    1,
                    'R'
                );
            }

            if ($mobal < 0) {
                $dtot = $dtot + $opening;
            } else {
                $ctot = $ctot + $opening;
            }
            $pdf->SetFont('Arial', 'B', 8);

            $pdf->Cell(
                $dateW + $vouchW + $descW,
                6,
                'TOTAL',
                1,
                0,
                'R'
            );

            $pdf->Cell(
                $debitW,
                6,
                number_format(abs($dtot), 2),
                1,
                0,
                'R'
            );

            $pdf->Cell(
                $creditW,
                6,
                number_format(abs($ctot), 2),
                1,
                0,
                'R'
            );

            $pdf->Cell(
                $balW,
                6,
                number_format(abs($totbal), 2) . ' ' . $mdctot,
                1,
                1,
                'R'
            );

            $pdf->Ln(3);
        }
    }

    ob_clean();
    $pdf->Output("$formname.pdf", "I");
}
