<?php
defined('BASEPATH') or exit('No direct script access allowed');
require_once APPPATH . "/third_party/pdf/fpdm.php";
require_once APPPATH . "/third_party/fpdf.php";
class MyPDF extends FPDF
{
    public $HeaderText = "Report Header Goes Here";
    public $SubHeaderText = "";
    public $HeaderColumns = array();
    public $printedBy;
    public $pages = "";
    function Header()
    {
        $this->Image(site_url("images/logo.png"), 8, 10, 40);
        $this->SetFont('Helvetica', 'B', 12);
        $this->Cell(0, 10, $this->HeaderText, 0, 1, 'C');
        $this->SetFont('Helvetica', 'B', 10);
        $this->Cell(0, 10, $this->SubHeaderText, 0, 1, 'C');
        $this->SetFont('Helvetica', '', 8);
        $this->Cell(0, 10, "Printed On: " . Today() . " / " . NepaliDate(Today()), 0, 0, 'R');
        if (isset($this->HeaderColumns)) {
            $this->Ln();
            $this->SetFillColor(232, 232, 232);
            $this->SetFont('Helvetica', 'B', 10);
            //$pdf->SetXY(10, 40);
            foreach ($this->HeaderColumns as $column) {
                $this->Cell($column['width'], 10, strtoupper($column['name']), 1, 0, 'L', 1);
            }
            $this->Ln();
        }
        // Line break
        // $this->Ln(20);
    }
    function Footer()
    {
        // Page footer
        //$this->SetY(-70);
        $this->ln(20);
        $this->SetFont('Helvetica', 'I', 8);
        $this->Cell(25, 1, $this->printedBy, 0, 1, 'C');
        $this->Cell(25, 1, '_________________', 0, 0, 'C');
        $this->setX(95);
        $this->Cell(25, 1, '_________________', 0, 0, 'C');
        $this->setX(170);
        $this->Cell(25, 1, '_________________', 0, 1, 'C');
        $this->Cell(25, 10, 'Printed By', 0, 0, 'C');
        $this->setX(95);
        $this->Cell(25, 10, 'Checked By', 0, 0, 'C');
        $this->setX(170);
        $this->Cell(25, 10, 'Approved By', 0, 1, 'C');
        $this->SetFont('Helvetica', 'I', 8);
        $this->SetTextColor(128);
        $this->Cell(0, 10, 'Page ' . $this->PageNo(), 0, 0, 'C');
    }
}
class myaccounts
{
    public function __construct()
    {
        // die;
        $this->initDatabase();
    }
    function voucherPDF($voucher_id)
    {
        $CI = &get_instance();
        $CI->load->library("numbertoword");
        $q = "select *,(select voucher_no from tbl_vouchers where tbl_vouchers.voucher_id=tbl_voucherdetails.voucher_id) as voucher_no, (select account_name from tbl_accounts where tbl_accounts.account_id=tbl_voucherdetails.account_id) as account_name from tbl_voucherdetails where voucher_id='$voucher_id'";
        $VoucherDetails = $CI->db->query($q)->result();
        $i = 0;
        $crTotal = 0;
        $drTotal = 0;
        $fields = array();
        foreach ($VoucherDetails as $VoucherDetail) :
            $i++;
            $fields['account_name_' . $i] = $VoucherDetail->account_name;
            $fields['narration_' . $i] = $VoucherDetail->narration;
            $fields['debit_amount_' . $i] = ($VoucherDetail->dr == 0) ? "" : N2($VoucherDetail->dr);
            $fields['credit_amount_' . $i] = ($VoucherDetail->cr == 0) ? "" : N2($VoucherDetail->cr);
            $crTotal += $VoucherDetail->cr;
            $drTotal += $VoucherDetail->dr;
        endforeach;
        $fields['voucher_no'] = $VoucherDetails[0]->voucher_no;
        $fields['transaction_date_ad'] = $VoucherDetails[0]->transaction_date;
        $fields['transaction_date_bs'] = NepaliDate($VoucherDetails[0]->transaction_date);
        $fields['prepared_by'] = $VoucherDetails[0]->created_by;
        $fields['voucher_no'] = $VoucherDetails[0]->voucher_no;
        $fields['debit_total'] = N2($drTotal);
        $fields['credit_total'] = N2($crTotal);
        if ($CI->session->userdata("language") == "np")
            $fields['amount_in_words'] = trim($CI->numbertoword->nepali_word($crTotal));
        else
            $fields['amount_in_words'] = trim($CI->numbertoword->english_word($crTotal));
        $file = APPPATH . "/../pdf/e_voucher1.pdf";
        $pdf = new FPDM($file);
        //pre($pdf->getContent($file,"PDF"));
        $pdf->Load($fields, true);
        $pdf->Merge();
        //$pdf->Flatten();
        $OutputFileLocation = APPPATH . "/../pdf/vouchers/";
        $OutputFile = "Voucher_" . $VoucherDetails[0]->voucher_no . ".pdf";
        $pdf->Output("F", $OutputFileLocation . $OutputFile);
        return $OutputFile;
    }
    function getVoucherTypes()
    {
        $CI = &get_instance();
        $VoucherType = $CI->db->query("select * from tbl_vouchertypes where status=1 order by voucher_name asc");
        return ($VoucherType->num_rows() > 0) ? $VoucherType->result() : false;
    }
    function getVoucherType($vouchertype_alias)
    {
        $CI = &get_instance();
        if (ctype_digit($vouchertype_alias)) {
            $t = "select * from tbl_vouchertypes where vouchertype_id='$vouchertype_alias'";
            $VoucherType = $CI->db->query($t);
            // echo $t;
        } else {
            $t = "select * from tbl_vouchertypes where voucher_alias='$vouchertype_alias'";
            $VoucherType = $CI->db->query($t);
            // echo $t;
        }
        return ($VoucherType->num_rows() > 0) ? $VoucherType->row() : false;
    }
    function getAccountDetails($account_id)
    {
        $CI = &get_instance();
        $Account = $CI->db->query("select * from tbl_accounts where account_id='$account_id'")->row();
        $Account->Balance = $this->getBalance($account_id);
        return $Account;
    }
    function getBalance($account_id)
    {
        $drTotal = getDrTotal($account_id);
        $crTotal = getCrTotal($account_id);
        return $drTotal - $crTotal;
    }
    function getOldBalance($account_id, $tillDate)
    {
        if ($tillDate == "") $tillDate = NepalitoEnglishDate(FYStart());
        $t = "select sum(dr) as debitBalance, sum(cr) as creditBalance from tbl_voucherdetails where account_id='$account_id' and transaction_date< '$tillDate'";
        $CI = &get_instance();
        $Query = $CI->db->query($t);
        $Result = $Query->row();
        $oldBalance = new stdClass;
        $oldBalance->debitBalance = $Result->debitBalance;
        $oldBalance->creditBalance = $Result->creditBalance;
        $oldBalance->balance = ($oldBalance->debitBalance - $oldBalance->creditBalance);
        return $oldBalance;
    }
    function getDrTotal($account_id)
    {
        $ci = &get_instance();
        return $ci->db->where("status", 1)->where("account_id", $account_id)->select_sum('dr')->get("tbl_voucherdetails")->row()->dr;
    }
    function getCrTotal($account_id)
    {
        $ci = &get_instance();
        return $ci->db->where("status", 1)->where("account_id", $account_id)->select_sum('cr')->get("tbl_voucherdetails")->row()->cr;
    }
    function getAllAccountsTable($accategory_id = "", $full = "")
    {
        $CI = &get_instance();
        if ($accategory_id != "") {
            $CI->db->where("status", 1)->where("accategory_id", $accategory_id);
        }
        if (isset($_GET['accategory_id'])) {
            $CI->db->where("status", 1)->where("accategory_id", $_GET['accategory_id']);
        } else {
            $CI->db->where("status", 1);
        }
        $CI->db->order_by("account_name ASC");
        $Accounts = $CI->db->get("tbl_accounts")->result();
        foreach ($Accounts as $Account) {
            $Account->Group = $CI->db->query("select * from tbl_acgroups where acgroup_id=(select acgroup_id from tbl_accategories where accategory_id = $Account->accategory_id)")->row();
            $Account->Category = $CI->db->query("select * from tbl_accategories where accategory_id = $Account->accategory_id")->row();
        }
        //$q=$CI->db->get_compiled_select();
        //print($q);
?>
        <div class="row mb-3">
            <?php if ($accategory_id == "") : ?>
                <div class="col">
                    <form method="get">
                        <div class="row">
                            <div class="col-5">
                                <?php $this->showAccountsCategoriesCombo("accategory_id", "", "accategory_id"); ?>
                            </div>
                            <div class="col-3">
                                <input type="submit" value="Show Accounts" class="form-control btn btn-success">
                            </div>
                        </div>
                    </form>
                </div> <?php endif; ?>
            <!-- <div id="dataTable_commands" class="col text-right"></div> -->
        </div>
        <?php
        $html = "";
        $html .= "<table class='table table-bordered table-striped longdataTable'>";
        $html .= "<thead>";
        $html .= "<tr><th>Account</th><th class='text-center'>Account Group</th><th class='text-center'>Dr</th><th class='text-center'>Cr</th><th class='text-center'>Action</th></tr>";
        $html .= "</thead><tbody>";
        $sn = 0;
        $BalanceTotal = 0;
        foreach ($Accounts as $Account) : $sn++;
            $balance = getBalance($Account->account_id);
            $BalanceTotal += $balance;
            // pre($Account);
            $html .= "<tr><td><a href='#' onClick='showLedger(" . $Account->account_id . ")'>" . $Account->account_name . "</a></td><td class='col-2'>" . $Account->Category->accategory_name . "</td><td class='col-1'>" . (($balance >= 0) ? myCurrency($balance) : "") . "</td><td class='col-1'>" . (($balance < 0) ? myCurrency(abs($balance)) : "") . "</td><td class='col-2 text-center'><a title='Show Ledger' class='btn btn-info btn-xs ' onClick='showLedger(" . $Account->account_id . ")'><i class='fa fa-eye'></i></a></td></tr>";
        endforeach;
        $html .= "</tbody><tfoot>";
        if ($full==""){
            $html .= "<tr><th colspan=2 class='text-right '>Total</th><th class='text-right'>" . myCurrency($BalanceTotal) . "</th><th class='text-right'>" . myCurrency($BalanceTotal) . "</th><th></th><th></th></tr>";
        }
        $html .= "</tfoot></table>\n";
        $html .= " <div class=\"modal fade\" id=\"ledgerdetails_box\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"ledgerdetails_box\" aria-hidden=\"true\">
        <div class=\"modal-dialog modal-xl\" role=\"document\">
            <div class=\"modal-content\">
                <div class=\"modal-header\">
                    <h5 class=\"modal-title\" id=\"exampleModalLabel\">Ledger Details</h5>
                    <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\">
                        <span aria-hidden=\"true\">&times;</span>
                    </button>
                </div>
                <div class=\"modal-body\" id=\"details_container\">
                    Ledger Details Goes Here
                </div>
                <!--<div class=\"modal-footer\">
                   <button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\">Close</button>
                   <button type=\"button\" class=\"btn btn-success\" data-dismiss=\"modal\">Print</button>
                </div>-->
            </div>
        </div>
    </div>";
        $html .= '<script>function showLedger(id) {$.ajax({url: \'';
        $html .= site_url("accounts/reports/ajax/getledgersummary/");
        $html .= '\' + id,success: function(data) {$(\'#ledgerdetails_box #details_container\').html(data);$(\'#ledgerdetails_box\').modal(\'show\');}});}</script>';
        echo $html;
    }
    function getAccountsTableByCategory($accategory_id)
    {
        $CI = &get_instance();
        $Accounts = $CI->db->where("accategory_id", $accategory_id)->where("status", 1)->order_by("account_name ASC")->get("tbl_accounts")->result();
        $html = "<h5 class='text-center'>Accounts Under " . getFieldfromValue("tbl_accategories", "accategory_name", "accategory_id", $accategory_id) . "</h5>";
        $html .= "<table class='table table-bordered dataTable'>";
        $html .= "<thead>";
        $html .= "<tr><th>Sn</th><th>Account</th><th>Dr/Cr</th><th>Action</th></tr>";
        $html .= "</thead><tbody>";
        $sn = 0;
        foreach ($Accounts as $Account) : $sn++;
            $html .= "<tr><td class='col-1'>" . $sn . "</td><td>" . $Account->account_name . "</td><td class='col-3'>" . myCurrency(getBalance($Account->account_id)) . "</td><td class='col-2'><a title='Show Ledger' class='btn btn-success btn-xs ' onClick='showLedger(" . $Account->account_id . ")'><i class='fa fa-eye'></i></a></td></tr>";
        endforeach;
        $html .= "</tbody></table>";
        echo $html;
    }
    //ACCOUNT HEADS
    function getCrAccountOpeningBalance($account_id)
    {
        $CI = &get_instance();
        $CI->db->select('*');
        $CI->db->from('tbl_voucherdetails');
        $CI->db->where('account_id', $account_id);
        $CI->db->where('voucher_id', 0);
        $query = $CI->db->get();
        if ($query->num_rows() > 0) {
            $result = $query->row();
            $balance = $result->cr;
            return $balance;
        } else {
            return 0;
        }
    }
    function getDrAccountOpeningBalance($account_id)
    {
        $CI = &get_instance();
        $CI->db->select('*');
        $CI->db->from('tbl_voucherdetails');
        $CI->db->where('account_id', $account_id);
        $CI->db->where('voucher_id', 0);
        $query = $CI->db->get();
        if ($query->num_rows() > 0) {
            $result = $query->row();
            $balance = $result->dr;
            return $balance;
        } else {
            return 0;
        }
    }
    function getAccountBalanceByAccountCategory($accategory_id)
    {
        $CI = &get_instance();
        $t = "select * from tbl_voucherdetails where 
        status=1 and
        account_id in (select account_id from tbl_accounts where accategory_id ='$accategory_id') or
        account_id in (select account_id from tbl_accounts where accategory_id in (select accategory_id from tbl_accategories where tbl_accategories.parent_category_id = '$accategory_id'))
        ";
        $Vouchers = $CI->db->query($t)->result();
        $DrBalance = 0;
        $CrBalance = 0;
        foreach ($Vouchers as $Voucher) {
            //pre($Voucher);die;
            $DrBalance += $Voucher->dr;
            $CrBalance += $Voucher->cr;
        }
        return ($DrBalance) - ($CrBalance);
    }
    function getAccountBalanceByAccountCategoryBothSide($accategory_id)
    {
        $CI = &get_instance();
        $t = "select * from tbl_voucherdetails where account_id in (select account_id from tbl_accounts where accategory_id ='$accategory_id')";
        $Vouchers = $CI->db->query($t)->result();
        $DrBalance = 0;
        $CrBalance = 0;
        foreach ($Vouchers as $Voucher) {
            $DrBalance += $Voucher->dr;
            $CrBalance += $Voucher->cr;
        }
        return ["DrBalance" => $DrBalance, "CrBalance" => $CrBalance];
    }
    function getAccountBalance($account_id)
    {
        $CI = &get_instance();
        $t = "select * from tbl_voucherdetails where account_id ='$account_id'"; //in (select account_id from tbl_accounts where accategory_id ='$accategory_id')";
        $Vouchers = $CI->db->query($t)->result();
        $DrBalance = 0;
        $CrBalance = 0;
        foreach ($Vouchers as $Voucher) {
            $DrBalance += $Voucher->dr;
            $CrBalance += $Voucher->cr;
        }
        return ($DrBalance) - ($CrBalance);
    }
    function getAccountBalanceBothSide($account_id)
    {
        $CI = &get_instance();
        $t = "select * from tbl_voucherdetails where account_id ='$account_id'"; //in (select account_id from tbl_accounts where accategory_id ='$accategory_id')";
        $Vouchers = $CI->db->query($t)->result();
        $DrBalance = 0;
        $CrBalance = 0;
        foreach ($Vouchers as $Voucher) {
            $DrBalance += $Voucher->dr;
            $CrBalance += $Voucher->cr;
        }
        return ["DrBalance" => $DrBalance, "CrBalance" => $CrBalance];
    }
    function getAccountGroups()
    {
        $CI = &get_instance();
        $t = "select * from tbl_acgroups where status=1";
        $AccountGroups = $CI->db->query($t)->result();
        foreach ($AccountGroups as $AccountGroup) :
            $AccountGroup->dr = 0;
            $AccountGroup->cr = 0;
            //    $TotalBalance = $this->getTotalBalanceByAccountGroup($AccountGroup->acgroup_id);
            $ACBalances = array();
            $TotalBalance = $this->getAccountBalanceR("Types", $AccountGroup->acgroup_id, $ACBalances);
            if ($AccountGroup->posting_side == "DR") {
                $AccountGroup->dr = ($TotalBalance);
            } else {
                $AccountGroup->cr = ($TotalBalance);
            }
        endforeach;
        $dr = 0;
        $cr = 0;
        return $AccountGroups;
    }
    public function getParentAccountCategories($acgroup_id = 0)
    {
        if (isset($_GET['group'])) {
            $acgroup_id = ($_GET['group']) ? $_GET['group'] : $acgroup_id;
        }
        $ci = &get_instance();
        if ($acgroup_id == 0)
            $t = "select * from tbl_accategories as b where status=1 and parent_category_id=0";
        else
            $t = "select * from tbl_accategories as b where status=1 and parent_category_id=0 and acgroup_id='$acgroup_id'";
        $AccountCategories = $ci->db->query($t)->result();
        foreach ($AccountCategories as $AccountCategory) :
            $AccountCategory->dr = 0;
            $AccountCategory->cr = 0;
            $AccountCategory->AccountGroup = $ci->db->query("select * from tbl_acgroups where acgroup_id = '$AccountCategory->acgroup_id'")->row();
            if ($AccountCategory->parent_category_id <> 0) {
                $AccountCategory->Parent = $ci->db->query("select * from tbl_accategories where accategory_id = '$AccountCategory->parent_category_id'")->row();
            }
            // $AccountCategory->Balance = $this->getAccountBalanceByAccountCategory($AccountCategory->accategory_id);
            $AccountCategory->Balance = $this->getAccountBalanceR("Category", $AccountCategory->accategory_id);
            $AccountCategory->posting_side = getFieldfromValue("tbl_acgroups", "posting_side", "acgroup_id", $AccountCategory->acgroup_id);
            if ($AccountCategory->posting_side == "DR")
                $AccountCategory->dr = $AccountCategory->Balance;
            else
                $AccountCategory->cr = $AccountCategory->Balance;
        endforeach;
        return $AccountCategories;
    }
    public function getChildAccountCategories($accategory_id = 0)
    {
        if (isset($_GET['category'])) {
            $accategory_id = ($_GET['category']) ? $_GET['category'] : $accategory_id;
        }
        $ci = &get_instance();
        if ($accategory_id == 0)
            $t = "select * from tbl_accategories as b where status=1 and parent_category_id<>0";
        else
            $t = "select * from tbl_accategories as b where status=1 and parent_category_id='$accategory_id'";
        $AccountCategories = $ci->db->query($t)->result();
        foreach ($AccountCategories as $AccountCategory) :
            $AccountCategory->dr = 0;
            $AccountCategory->cr = 0;
            if ($AccountCategory->parent_category_id <> 0) {
                $AccountCategory->Parent = $ci->db->query("select * from tbl_accategories where accategory_id = '$AccountCategory->parent_category_id'")->row();
            }
            // $AccountCategory->Balance = $this->getAccountBalanceByAccountCategory($AccountCategory->accategory_id);
            $AccountCategory->Balance = $this->getAccountBalanceR("Group", $AccountCategory->accategory_id);
            $AccountCategory->posting_side = getFieldfromValue("tbl_acgroups", "posting_side", "acgroup_id", $AccountCategory->acgroup_id);
            if ($AccountCategory->posting_side == "DR")
                $AccountCategory->dr = $AccountCategory->Balance;
            else
                $AccountCategory->cr = $AccountCategory->Balance;
        endforeach;
        return $AccountCategories;
    }
    function getTotalBalanceByAccountGroup($acgroup_id)
    {
        $CI = &get_instance();
        $t = "select * from tbl_voucherdetails where account_id in (select account_id from tbl_accounts where accategory_id in (select accategory_id from tbl_accategories where acgroup_id='$acgroup_id'))";
        $Vouchers = $CI->db->query($t)->result();
        $DrBalance = 0;
        $CrBalance = 0;
        foreach ($Vouchers as $Voucher) {
            //pre($Voucher);die;
            $DrBalance += $Voucher->dr;
            $CrBalance += $Voucher->cr;
        }
        return ($DrBalance) - ($CrBalance);
    }
    function getParentAccountCategoriesByGroup($acgroup_id, $both = false)
    {
        $CI = &get_instance();
        $AccountCategories = $CI->db
            ->where("acgroup_id", $acgroup_id)
            ->where("status", 1)
            ->where("parent_category_id", 0)
            ->order_by("accategory_name ASC")->get("tbl_accategories")->result();
        foreach ($AccountCategories as $AccountCategory) {
            $AccountCategory->dr = 0;
            $AccountCategory->cr = 0;
            if ($both) {
                $TotalBalance = $this->getAccountBalanceByAccountCategoryBothSide($AccountCategory->accategory_id);
                $AccountCategory->dr = $TotalBalance['DrBalance'];
                $AccountCategory->cr = $TotalBalance['CrBalance'];
            } else {
                $AccountCategory->posting_side = getFieldfromValue("tbl_acgroups", "posting_side", "acgroup_id", $AccountCategory->acgroup_id);
                $TotalBalance = $this->getAccountBalanceByAccountCategory($AccountCategory->accategory_id);
                if ($AccountCategory->posting_side == "DR") {
                    $AccountCategory->dr = abs($TotalBalance);
                } else {
                    $AccountCategory->cr = abs($TotalBalance);
                }
            }
        }
        return $AccountCategories;
    }
    function getChildAccountCategoriesByGroupAndParentCategory($acgroup_id, $accategory_id, $both = false)
    {
        $CI = &get_instance();
        $AccountCategories = $CI->db
            ->where("acgroup_id", $acgroup_id)
            ->where("parent_category_id", $accategory_id)
            ->where("status", 1)
            ->order_by("accategory_name ASC")->get("tbl_accategories")->result();
        foreach ($AccountCategories as $AccountCategory) {
            $AccountCategory->dr = 0;
            $AccountCategory->cr = 0;
            if ($both) {
                $TotalBalance = $this->getAccountBalanceByAccountCategoryBothSide($AccountCategory->accategory_id);
                $AccountCategory->dr = $TotalBalance['DrBalance'];
                $AccountCategory->cr = $TotalBalance['CrBalance'];
            } else {
                $TotalBalance = $this->getAccountBalanceByAccountCategory($AccountCategory->accategory_id);
                $AccountCategory->posting_side = getFieldfromValue("tbl_acgroups", "posting_side", "acgroup_id", $AccountCategory->acgroup_id);
                if ($AccountCategory->posting_side == "DR") {
                    $AccountCategory->dr = abs($TotalBalance);
                } else {
                    $AccountCategory->cr = abs($TotalBalance);
                }
            }
        }
        return $AccountCategories;
    }
    function getAccountsByCategory($accategory_id, $getOldBalance = false)
    {
        $CI = &get_instance();
        $AccountHeads = $CI->db
            ->where("accategory_id", $accategory_id)
            ->where("status", 1)
            ->order_by("account_name ASC")->get("tbl_accounts")->result();
        foreach ($AccountHeads as $AccountHead) {
            $AccountHead = $this->CompileAccount($AccountHead, $getOldBalance);
        }
        return $AccountHeads;
    }
    function getAccountHeads($getOldBalance = false)
    {
        $CI = &get_instance();
        $AccountHeads =  $CI->db->query("select * from tbl_accounts where status=1 order by accategory_id asc,account_name asc ")->result();
        foreach ($AccountHeads as $AccountHead) {
            $AccountHead = $this->CompileAccount($AccountHead, $getOldBalance);
        }
        return $AccountHeads;
    }
    function CompileAccount($AccountHead, $getOldBalance = false)
    {
        $CI = &get_instance();
        $AccountHead->Group = $CI->db->query("select * from tbl_accategories where accategory_id='$AccountHead->accategory_id'")->row();
        if ($AccountHead->Group) {
            if ($AccountHead->Group->parent_category_id != 0)
                $AccountHead->Category = $CI->db->query("select * from tbl_accategories where accategory_id='" . $AccountHead->Group->parent_category_id . "'")->row();
            else
                $AccountHead->Category = $CI->db->query("select * from tbl_accategories where accategory_id='" . $AccountHead->Group->accategory_id . "'")->row();
            $AccountHead->Type = $CI->db->query("select * from tbl_acgroups where acgroup_id='" . $AccountHead->Group->acgroup_id . "'")->row();
        }
        if ($getOldBalance) {
            $AccountHead->dr_opening_balance = $this->getDrAccountOpeningBalance($AccountHead->account_id);
            $AccountHead->cr_opening_balance = $this->getCrAccountOpeningBalance($AccountHead->account_id);
        }
        $TotalBalances = array();
        $TotalBalance = $this->getAccountBalanceR("Account", $AccountHead->account_id, $TotalBalances);
        $AccountHead->cr = $TotalBalances["DrBalance"];
        $AccountHead->dr = $TotalBalances["CrBalance"];
        return $AccountHead;
    }
    function listAccountHeads()
    {
        ?>
        <?php $d = 0;
        $c = 0;
        $TableData =  $this->getAccountHeads(true); ?>
        <!-- <div id="dataTable_wrapper" class="mb-20">
            <div class="col"></div>
            <div class="col text-right"></div>
        </div> -->
        <table class="table table-striped table-bordered  longdataTable">
            <thead>
                <tr>
                    <!-- <th class="col-1.5" rowspan="2"><?php //myLang(" Category"); 
                                                            ?></th> -->

                    <th class="col-1.5" rowspan="2"><?php myLang("Ledger"); ?></th>
                    <th class="col-1.5" rowspan="2"><?php myLang(" Group"); ?></th>
                    <th colspan="2" class="col-3 text-center">Opening Balance</th>
                    <th class="col-2 text-center" rowspan="2"><?php myLang("Action"); ?></th>
                </tr>
                <tr>
                    <!-- <th class="col-1"><?php //myLang(" Type"); 
                                            ?></th> -->
                    <!-- <th class="col-1.5"><?php //myLang(" Category"); 
                                                ?></th> -->
                    <!-- <th class="col-1.5"><?php //myLang(" Group"); 
                                                ?></th> -->
                    <!-- <th class="col-1.5"><?php //myLang("Ledger"); 
                                                ?></th> -->
                    <th class="col-1 text-center"><?php myLang("Dr"); ?></th>
                    <th class="col-1 text-center"><?php myLang("Cr"); ?></th>
                    <!-- <th class="col-1"><?php //myLang("Party Name"); 
                                            ?></th> -->
                    <!-- <th class="col-1"><?php //myLang("Party Contact"); 
                                            ?></th> -->
                    <!-- <th class="col-1"><?php //myLang("PAN"); 
                                            ?></th> -->
                    <!-- <th class="col-1 text-center"><?php //myLang("Action"); 
                                                        ?></th> -->
                </tr>
            </thead>
            <tbody>
                <?php $sn = 0;
                foreach ($TableData as $TableRow) : $sn++; ?>
                    <?php foreach ($TableRow as $cols) : $id = $cols;
                        break;
                    endforeach; ?><tr>
                        <!-- <td><?php //echo isset($TableRow->Type) ? linkGroup($TableRow->Type) : ""; 
                                    ?></td> -->
                        <!-- <td><?php //echo isset($TableRow->Category) ? linkCategory($TableRow->Category) : ''; 
                                    ?></td> -->
                        <td><?php echo linkLedger($TableRow); ?></td>
                        <td><?php echo linkCategory($TableRow->Group); ?></td>
                        <td><?php $d += doubleval($TableRow->dr_opening_balance);
                            echo ($TableRow->dr_opening_balance > 0) ? myCurrency($TableRow->dr_opening_balance) : ""; ?></td>
                        <td><?php $c += doubleval($TableRow->cr_opening_balance);
                            echo ($TableRow->cr_opening_balance > 0) ? myCurrency($TableRow->cr_opening_balance) : ""; ?></td>
                        <!-- <td><?php //echo $TableRow->account_partyname; 
                                    ?></td> -->
                        <!-- <td><?php //echo $TableRow->account_partycontact; 
                                    ?></td> -->
                        <!-- <td><?php //echo $TableRow->account_partypan; 
                                    ?></td> -->
                        <td class="text-center">
                            <a onClick="javascript:showDetails(<?php echo $id; ?>);" class="btn btn-primary btn-xs"><i class="fas fa-copy"></i> </a>
                            <a href="<?php echo site_url("accounts/accountheads/edit/$id"); ?>" class="btn btn-info btn-xs"><i class="fas fa-edit"></i> </a>
                            <a onClick="javascript:doDelete(<?php echo $id; ?>);" class="btn btn-danger btn-xs"><i class="fas fa-trash"></i> </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <!-- Modal -->
        <div class="modal fade" id="accountdetails_box" tabindex="-1" role="dialog" aria-labelledby="accountdetails_box" aria-hidden="true">
            <div class="modal-dialog modal-xl" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Account Details</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body" id="details_container">
                        Account Details Goes Here
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <a class="btn btn-primary" id="details_edit_btn" href="">Edit</a>
                    </div>
                </div>
            </div>
        </div>
        <script>
            function doDelete(id) {
                if (confirm('Are you sure to delete?')) {
                    window.location = '<?php echo site_url("accounts/accountheads/delete/"); ?>' + id;
                }
            }

            function showDetails(id) {
                $.ajax({
                    url: "<?php echo site_url("accounts/accountheads/getdetails/"); ?>" + id,
                    success: function(data) {
                        $("#details_container").html(data);
                        $("#details_edit_btn").attr("href", "<?php echo site_url("accounts/accountheads/edit/"); ?>" + id);
                        $("#accountdetails_box").modal('show');
                    }
                });
            }
        </script>
    <?php
    }
    function getLedgerData($account_id, $fromDate = "", $toDate = "")
    {
        $oldBalance = $this->getOldBalance($account_id, $fromDate);
        $fromDate = ($fromDate == "") ? NepaliToEnglishDate(firstDayOfNepaliMonth()) : $fromDate;
        $toDate = ($toDate == "") ? Today() : $toDate;
        $ci = &get_instance();
        $q = "select *,(select bs_date from tbl_nepengcalendar where ad_date=tbl_voucherdetails.transaction_date) as transaction_date_bs from tbl_voucherdetails where status=1 and account_id='$account_id' and transaction_date>='$fromDate' and transaction_date<='$toDate'";
        // echo $q;
        $Transactions = $ci->db->query($q)->result();
        //        $Transactions = $ci->db->where("transaction_date>='$fromDate'")->where("transaction_date<='$toDate'")->where("status", 1)->where("account_id", $account_id)->get("tbl_voucherdetails")->result();
        $Account = $ci->db->where("status", 1)->where("account_id", $account_id)->get("tbl_accounts")->row();
        foreach ($Transactions as $T) {
            //$T->AccountCategory=$this->db->where("status",1)->where("accategory_id",$AccountGroup->acgroup_id)->get("tbl_accategories")->result();
            $T->Voucher = $ci->db->where("status", 1)->where("voucher_id", $T->voucher_id)->get("tbl_vouchers")->row();
        }
        $data['Transactions'] = $Transactions;
        $data['Account'] = $Account;
        $data['account_id'] = $account_id;
        $data['oldBalance'] = $oldBalance;
        return $data;
    }
    function showLedger($account_id, $fromDate = "", $toDate = "")
    {

        $oldBalance = $this->getOldBalance($account_id, FYStart());
        $fromDate = ($fromDate == "") ? NepaliToEnglishDate(FYStart()) : $fromDate;
        $toDate = ($toDate == "") ? Today() : $toDate;
        $ci = &get_instance();
        $Transactions = $ci->db->where("transaction_date between '$fromDate' AND '$toDate'")->where("status", 1)->where("account_id", $account_id)->get("tbl_voucherdetails")->result();

        $Account = $ci->db->where("status", 1)->where("account_id", $account_id)->get("tbl_accounts")->row();
        foreach ($Transactions as $T) {
            $T->Voucher = $ci->db->where("status", 1)->where("voucher_id", $T->voucher_id)->get("tbl_vouchers")->row();
        }
        $data['Transactions'] = $Transactions;
        $data['Account'] = $Account;
        $data['account_id'] = $account_id;
    ?>
        <div class="card-primary card-outline ">
            <div class="card-header">
                <h5 class="m-0">Leger for Account : <?php echo $Account->account_name; ?> <a href="<?php echo site_url("accounts/ledger/print/" . $Account->account_id . "/?" . $_SERVER['QUERY_STRING']); ?>" class="btn btn-success btn-sm float-right">Print</a></h5>
            </div>
            <div class="card-body  p-0 mb-20" id="printableDiv">
                <h3 class="text-center"><?php echo $ci->session->userdata("CompanyName"); ?></h3>
                <h5 class="text-center">Ledger Details for <?php echo $Account->account_name; ?> </h5>
                <?php $TableData = $Transactions; ?>
                <?php $TotalCols = 7; ?>
                <table class="table table-bordered table-head-fixed text-nowrap table-striped ">
                    <thead>
                        <tr>
                            <th class="col-1"><?php myLang("Date"); ?></th>
                            <!-- <th class="col-1">Date (A.D)</th> -->
                            <th class="col-1"><?php myLang("Account"); ?></th>
                            <!-- <th class="col-5">Narration</th> -->
                            <th class="col-1"><?php myLang("Voucher Type"); ?></th>
                            <th class="col-1 text-right"><?php myLang("Debit"); ?></th>
                            <th class="col-1 text-right"><?php myLang("Credit"); ?></th>
                            <th class="col-1"><?php myLang("Balance"); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $r = 1;
                        $drTotal = 0;
                        $crTotal = 0;
                        $balance = 0;

                        foreach ($TableData as $TableRow) : $r++;
                        ?>
                            <tr>
                                <td><?php echo NepaliDate(($TableRow->transaction_date)); ?></td>

                                <td>
                                    <?php
                                    if ($TableRow->voucher_id != 0) :
                                        $Tr = $ci->myaccounts->getVoucherTransactions($TableRow->Voucher->voucher_id);
                                        foreach ($Tr as $T) :
                                            if ($T->account_id != $account_id) {
                                                echo $T->account_name;
                                                break;
                                            }

                                        endforeach;

                                    // pre($Tr);
                                    else :
                                        echo "Opening Balance";
                                    endif;
                                    ?></td>
                                <!-- <td><?php //echo $TableRow->narration; 
                                            ?></td> -->
                                <td>
                                    <?php linkVoucher($TableRow->voucher_id);  ?>

                                </td>
                                <td><?php echo myCurrency($TableRow->dr);
                                    $drTotal += $TableRow->dr; ?></td>
                                <td><?php echo myCurrency($TableRow->cr);
                                    $crTotal += $TableRow->cr; ?></td>
                                <?php $balance += $TableRow->dr;
                                $balance -= $TableRow->cr; ?>
                                <td><?php echo ($balance != 0) ? myCurrency($balance) : showNill(); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php while ($r < 15) : ?>
                            <tr>
                                <td>&nbsp;</td>
                                <!-- <td></td> -->
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                        <?php $r++;
                        endwhile; ?>
                    <tbody>
                    <tfoot>
                        <tr>
                            <td colspan="3" class="text-right text-bold">Total</td>
                            <td><?php echo myCurrency($drTotal); ?></td>
                            <td><?php echo myCurrency($crTotal); ?></td>
                            <td><?php echo myCurrency($balance); ?></td>
                        </tr>
                    </tfoot>
                </table>
                <!-- <div class="container ">
                <div class="row mt-100 ">
                    <div class="col-2"><span class="underline-text"><?php echo $ci->session->userdata("loggedUser"); ?></span></div>
                    <div class="col-2 offset-3">______________</div>
                    <div class="col-2 offset-3">______________</div>
                </div>
                <div class="row">
                    <div class="col-2">Entered By</div>
                    <div class="col-2 offset-3">Checked By</div>
                    <div class="col-2 offset-3">Approved By</div>
                </div>
                <div class="divFooter">UNCLASSIFIED</div>
            </div> -->
            </div>
        </div>
    <?php
    }
    function ledgerPDF_FPDM($account_id, $fromDate, $toDate)
    {
        $CI = &get_instance();
        $CI->load->library("numbertoword");
        $ledgerData = $this->getLedgerData($account_id, $fromDate, $toDate);
        $file = APPPATH . "/../pdf/e_ledger1.pdf";
        $pdf = new FPDM($file);
        $i = 0;
        $crTotal = 0;
        $drTotal = 0;
        $fields = array();
        $lineBalance = 0;
        // pre($ledgerData);
        //die;
        $fields['account_name'] = $ledgerData['Account']->account_name;
        $fields['from_date_ad'] = NepaliToEnglishDate($fromDate);
        $fields['to_date_ad'] = NepaliToEnglishDate($toDate);
        $fields['from_date_bs'] = $fromDate;
        $fields['to_date_bs'] = $toDate;
        $printedDate = NepaliDate(Today()) . "(AD: " . Today() . ")";
        foreach ($ledgerData['Transactions'] as $VoucherDetail) :
            $i++;
            $fields['date' . $i] = $VoucherDetail->transaction_date . chr(13) . NepaliDate($VoucherDetail->transaction_date);
            $fields['voucher_no' . $i] = isset($VoucherDetail->Voucher->voucher_no) ? $VoucherDetail->Voucher->voucher_no : "B/F";
            $fields['narration' . $i] = $VoucherDetail->narration;
            $fields['debit' . $i] = ($VoucherDetail->dr == 0) ? "" : N2($VoucherDetail->dr);
            $fields['credit' . $i] = ($VoucherDetail->dr == 0) ? N2($VoucherDetail->cr) : "";
            $drTotal += $VoucherDetail->dr;
            $crTotal += $VoucherDetail->cr;
            $lineBalance += $VoucherDetail->dr - $VoucherDetail->cr;
            $fields['balance' . $i] = N2($lineBalance);
            $fields['debit_total'] = $drTotal;
            $fields['credit_total'] = $crTotal;
            $fields['balance_total'] = $crTotal - $drTotal;
            $fields['printed_by'] = $CI->session->userdata("loggedUser");
            $fields['printed_on'] = $printedDate;
            $pdf->Load($fields, true);
            if ($i > 20) {
                //$pdf->AddPage();
                $i = 0;
            }
        endforeach;
        //$pdf->Load($fields, true);
        $pdf->Merge();
        //$pdf->Flatten();
        $OutputFileLocation = APPPATH . "/../pdf/ledgers/";
        $OutputFile = "Ledger_" . $ledgerData['Account']->account_id . ".pdf";
        $pdf->Output("F", $OutputFileLocation . $OutputFile);
        return $OutputFile;
    }
    function ledgerPDF($account_id, $fromDate, $toDate)
    {
        $CI = &get_instance();
        $CI->load->library("numbertoword");
        $ledgerData = $this->getLedgerData($account_id, $fromDate, $toDate);
        if ($_SERVER['HTTP_HOST'] == 'localhost')
            $file = "ledger_$account_id.wpdf";
        else
            $file = "ledger_$account_id.pdf";
        $pdf = new MyPDF();
        $pdf->HeaderText = "Account Ledger for " . $ledgerData['Account']->account_name;
        $pdf->SubHeaderText = "Period of $fromDate to $toDate";
        $pdf->printedBy = $CI->session->userdata('loggedUser');
        $i = 0;
        $crTotal = 0;
        $drTotal = 0;
        $fields = array();
        $lineBalance = 0;
        // pre($ledgerData);
        //die;
        $columns = array(
            array("name" => "Date",  "width" => 20, "align" => "C"),
            array("name" => "VN", "width" => 10, "align" => "L"),
            array("name" => "Narration", "width" => 80, "align" => "L"),
            array("name" => "Debit", "width" => 25, "align" => "L"),
            array("name" => "Credit", "width" => 25, "align" => "L"),
            array("name" => "Balance", "width" => 25, "align" => "L")
        );
        $pdf->HeaderColumns = $columns;
        $pdf->SetAutoPageBreak(true, 50);
        $pdf->AddPage("P", "A4");
        $pdf->SetFont('Helvetica', '', 8);
        $y = 50;
        $rowHeight = 8;
        foreach ($ledgerData['Transactions'] as $VoucherDetail) :
            $pdf->cell($columns[0]['width'], $rowHeight, $VoucherDetail->transaction_date, 1, 0, "C");
            $pdf->cell($columns[1]['width'], $rowHeight, isset($VoucherDetail->Voucher->voucher_no) ? $VoucherDetail->Voucher->voucher_no : "B/F", 1, 0, "C");
            $pdf->cell($columns[2]['width'], $rowHeight, character_limiter($VoucherDetail->narration, 35, " ..."), 1, 0, "J");
            $pdf->cell($columns[3]['width'], $rowHeight, ($VoucherDetail->dr == 0) ? "" : N2($VoucherDetail->dr), 1, 0, "R");
            $pdf->cell($columns[4]['width'], $rowHeight, ($VoucherDetail->dr == 0) ? N2($VoucherDetail->cr) : "", 1, 0, "R");
            $drTotal += $VoucherDetail->dr;
            $crTotal += $VoucherDetail->cr;
            $lineBalance += $VoucherDetail->dr - $VoucherDetail->cr;
            $pdf->cell($columns[5]['width'], $rowHeight,  N2($lineBalance), 1, 0, "R");
            $pdf->Ln();
        // $x = 10;
        // $pdf->SetXY($x, $y);
        // $pdf->Cell($columns[0]['width'], $rowHeight, $VoucherDetail->transaction_date, 1, "C");
        // $pdf->SetXY($x += $columns[0]['width'], $y);
        // $pdf->MultiCell($columns[1]['width'], $rowHeight, isset($VoucherDetail->Voucher->voucher_no) ? $VoucherDetail->Voucher->voucher_no : "B/F", 1, "C");
        // $pdf->SetXY($x += $columns[1]['width'], $y);
        // $pdf->MultiCell($columns[2]['width'], $rowHeight, $VoucherDetail->narration, 1, "J", false, 1);
        // $pdf->SetXY($x += $columns[2]['width'], $y);
        // $pdf->MultiCell($columns[3]['width'], $rowHeight, ($VoucherDetail->dr == 0) ? "" : N2($VoucherDetail->dr), 1,"R");
        // $pdf->SetXY($x += $columns[3]['width'], $y);
        // $pdf->MultiCell($columns[4]['width'], $rowHeight, ($VoucherDetail->dr == 0) ? N2($VoucherDetail->cr) : "", 1,"R");
        // $drTotal += $VoucherDetail->dr;
        // $crTotal += $VoucherDetail->cr;
        // $lineBalance += $VoucherDetail->dr - $VoucherDetail->cr;
        // $pdf->SetXY($x += $columns[4]['width'],$y);
        // $pdf->MultiCell($columns[5]['width'], $rowHeight,  N2($lineBalance), 1,"R");
        // $pdf->Ln();
        // $y += $rowHeight;
        // if($y>280)$pdf->AddPage();
        endforeach;
        $pdf->Output(APPPATH . "/../pdf/ledgers/" . $file, "F");
        return $file;
        // $printedDate = NepaliDate(Today()) . "(AD: " . Today() . ")";
        // foreach ($ledgerData['Transactions'] as $VoucherDetail) :
        //     $i++;
        //     $fields['date' . $i] = $VoucherDetail->transaction_date . chr(13) . NepaliDate($VoucherDetail->transaction_date);
        //     $fields['voucher_no' . $i] = isset($VoucherDetail->Voucher->voucher_no) ? $VoucherDetail->Voucher->voucher_no : "B/F";
        //     $fields['narration' . $i] = $VoucherDetail->narration;
        //     $fields['debit' . $i] = ($VoucherDetail->dr == 0) ? "" : N2($VoucherDetail->dr);
        //     $fields['credit' . $i] = ($VoucherDetail->dr == 0) ? N2($VoucherDetail->cr) : "";
        //     $drTotal += $VoucherDetail->dr;
        //     $crTotal += $VoucherDetail->cr;
        //     $lineBalance += $VoucherDetail->dr - $VoucherDetail->cr;
        //     $fields['balance' . $i] = N2($lineBalance);
        //     $fields['debit_total'] = $drTotal;
        //     $fields['credit_total'] = $crTotal;
        //     $fields['balance_total'] = $crTotal - $drTotal;
        //     $fields['printed_by'] = $CI->session->userdata("loggedUser");
        //     $fields['printed_on'] = $printedDate;
        //     $pdf->Load($fields, true);
        //     if ($i > 20) {
        //         //$pdf->AddPage();
        //         $i = 0;
        //     }
        // endforeach;
        // //$pdf->Load($fields, true);
        // $pdf->Merge();
        // //$pdf->Flatten();
        // $OutputFileLocation = APPPATH . "/../pdf/ledgers/";
        // $OutputFile = "Ledger_" . $ledgerData['Account']->account_id . ".pdf";
        // $pdf->Output("F", $OutputFileLocation . $OutputFile);
        // return $OutputFile;
    }
    function listVouchers($fromDate = "", $toDate = "", $account_id = "", $vouchertype_id = "", $showAccounts = false, $showVoucherTypes = false)
    {
        // echo $toDate;
        $ci = &get_instance();
        $fromDate = ($fromDate == "") ? NepaliToEnglishDate(firstDayOfNepaliMonth()) : $fromDate;
        $toDate = ($toDate == "") ? Today() : $toDate;
        $q = "select *, (select narration from tbl_voucherdetails where tbl_voucherdetails.voucher_id=tbl_vouchers.voucher_id limit 1) as narration from tbl_vouchers where status=1 and voucher_date>='$fromDate' and voucher_date<='$toDate'";
        if ($account_id != "") $q .= " and voucher_id in (select voucher_id from tbl_voucherdetails where account_id='$account_id')";
        if ($vouchertype_id != "") $q .= " and voucher_type ='$vouchertype_id'";
        $q .= " order by voucher_date desc";
        // echo $q;
        $Vouchers = $ci->db->query($q)->result();
        $TableData = $Vouchers;
        if ($showAccounts) :
            foreach ($TableData as $Row) {
                $q = "select * from tbl_voucherdetails where voucher_id='" . $Row->voucher_id . "'";
                $Row->Transactions = $ci->db->query($q)->result();
                $Row->VoucherType = $this->getVoucherType($Row->voucher_type);
            }
        endif;
    ?>
        <table class="table table-bordered table-striped longdataTable" id="voucherList1">
            <thead>
                <tr>
                    <!-- <th class="col-1"><?php myLang("Sn"); ?></th> -->
                    <th class="" width="20" data-sortable="true"><?php myLang("#"); ?></th>
                    <th class="" width="70"><?php myLang("Date (B.S)"); ?></th>
                    <?php if ($showAccounts) : ?>
                        <th><?php myLang("Particulars"); ?></th>
                    <?php endif; ?>
                    <?php if ($showVoucherTypes) : ?>
                        <th><?php myLang("Voucher Type"); ?></th>
                    <?php endif; ?>
                    <th width="90"><?php myLang("Dr"); ?></th>
                    <th width="90"><?php myLang("Cr"); ?></th>
                    <!--<th><?php myLang("Voucher State"); ?></th> -->
                    <th class="table-col col-2">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php $a = 0; $drTotal=0;$crTotal=0;
                foreach ($TableData as $TableRow) : $a++; ?>

                    <tr data-id="<?php echo $TableRow->voucher_id; ?>" class="<?php echo ($TableRow->voucher_state == "Reversed") ? "table-danger" : ""; ?>">
                        <!-- <td><?php echo $TableRow->voucher_id; ?></td> -->
                        <td><?php echo $TableRow->voucher_no; ?></td>
                        <td><?php echo NepaliDate($TableRow->voucher_date); ?></td>
                        <td>
                            <?php foreach ($TableRow->Transactions as $Transaction) : ?>
                                <div><?php echo (($Transaction->cr) ? "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" : "") . $this->getAccountDetails($Transaction->account_id)->account_name; ?></div>
                            <?php endforeach; ?>
                            <?php if($TableRow->narration): ?>
                            (<span class="narration_display"><?php echo $TableRow->narration; ?></span>)
                            <?php endif; ?>
                        </td>
                        <?php if ($showVoucherTypes) : ?>
                            <td>
                                
                                <?php echo $TableRow->VoucherType->voucher_name; ?>

                            </td>
                        <?php endif; ?>
                        <td>
                            <?php foreach ($TableRow->Transactions as $Transaction) : $drTotal+=$Transaction->dr; ?>
                                <?php echo myCurrency($Transaction->dr); ?>
                            <?php endforeach; ?>
                        </td>
                        <td>
                            <?php foreach ($TableRow->Transactions as $Transaction) : $crTotal+=$Transaction->cr; ?>
                                <?php echo myCurrency($Transaction->cr); ?>
                            <?php endforeach; ?>
                        </td>
                        <!-- <td><?php echo $TableRow->voucher_type; ?></td> -->
                        <!-- <td><?php echo $TableRow->voucher_state; ?></td> -->
                        <td class="col-1">
                            <a onClick="javascript:showDetails(<?php echo $TableRow->voucher_id; ?>);" class="btn btn-success btn-xs" title="View Details"><i class="fa fa-eye"></i></a>
                            <a onClick="javascript:showPDF(<?php echo $TableRow->voucher_id; ?>);" class="btn btn-primary btn-xs" title="View PDF"><i class="fa fa-file-pdf"></i></a>
                            <a onClick="javascript:deleteVoucher(<?php echo $TableRow->voucher_id; ?>);" class="btn btn-danger btn-xs" title="Delete Voucher"><i class="fa fa-trash"></i></a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <tbody>
            <tfoot>
                <tr>
                    <td></td>
                    <td></td>
                    <?php if ($showVoucherTypes) : ?>
                        <td></td>
                    <?php endif; ?>
                    <td class="text-right text-bold">Total</td>
                    <td class="text-right text-bold"><?php echo myCurrency($drTotal); ?></td>
                    <td class="text-right text-bold"><?php echo myCurrency($crTotal); ?></td>
                    <td></td>
                </tr>
            </tfoot>
        </table>
        <div class="modal fade" id="voucherdetails_box" tabindex="-1" role="dialog" aria-labelledby="voucherdetails_box" aria-hidden="true">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <!-- <h5 class="modal-title" id="exampleModalLabel">Voucher Details</h5> -->
                        <!-- <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button> -->
                    </div>
                    <div class="modal-body" id="details_container">
                        Voucher Details Goes Here
                    </div>
                    <div class="modal-footer">
                        <button type="button" onClick='reversalEntry()' id="reversalBtn" class="btn btn-secondary" data-dismiss="modal" data-id="">Revarsal Entry</button>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
        <script>
            function showPDF(id) {
                $.ajax({
                    url: "<?php echo site_url("accounts/vouchers/print/"); ?>" + id + "?modal=true",
                    success: function(data) {
                        $("#details_container").html(data);
                        $("#reversalBtn").data("id", id);
                        $("#voucherdetails_box").modal('show');
                    }
                });
            }

            function showDetails(id) {
                $.ajax({
                    url: "<?php echo site_url("accounts/vouchers/voucherdetails/"); ?>" + id,
                    success: function(data) {
                        $("#details_container").html(data);
                        $("#reversalBtn").data("id", id);
                        $("#voucherdetails_box").modal('show');
                    }
                });
            }

            function reversalEntry() {
                var id = $("#reversalBtn").data("id");
                if (confirm("Are you sure you want to post reversal for this voucher?")) {
                    window.location = "<?php echo site_url("accounts/vouchers/reversal/"); ?>" + id;
                }
            }
        </script>
        <?php
        function footerfunctions()
        {
        ?>
            <script>
                $(document).ready(function() {
                    var table = $('#voucherList').DataTable();
                    var tableRows = $('table#voucherList tbody').find('tr');
                    tableRows.each(function() {
                        async: false;
                        var jqueryRow = $(this);
                        var row = table.row(jqueryRow);
                        var id = $(this).data("id");
                        var Transactions = "<table class='table table-resonsive'><tr><th>Account<\/th><th>Narration<\/th><th>Dr<\/th><th>Cr<\/th><\/tr><tr><td>Billable Projects<\/td><td>Website Development<\/td><td>50000<\/td><td>0<\/td><\/tr><tr><td>Larke Himal Jadibuti Udhyog<\/td><td>Website Development<\/td><td>0<\/td><td>50000<\/td><\/tr><\/table>";
                        Transactions = getVoucherDetails(id);
                        row.child(Transactions).show();
                    });
                });

                function getVoucherDetails(id) {
                    $.data;
                    $.ajax({
                        url: "<?php echo site_url("ajax/getVoucherDetailsTable/"); ?>" + id,
                        async: false,
                        success: function(data) {
                            $.data = data;
                        }
                    });
                    return ($.data);
                }

                function deleteVoucher(id) {
                    // Show confirmation dialog
                    if (confirm("Are you sure you want to delete this voucher?")) {
                        $.ajax({
                            url: "<?php echo site_url("ajax/deleteVoucher/"); ?>" + id,
                            async: false,
                            success: function(data) {
                                alert("Voucher deleted successfully.");
                                // Reload the page
                                location.reload();
                            },
                            error: function() {
                                alert("Failed to delete voucher.");
                            }
                        });
                    }
                }
            </script>
        <?php
        }
        ?>
    <?php
    }
    function showVoucherType($vouchertype_id)
    {
        $ci = &get_instance();
        $ci->db->where("status", 1)->where("vouchertype_id", $vouchertype_id);
        return $ci->db->get("tbl_vouchertypes")->row();
    }
    function deleteVoucher($voucher_id)
    {
        $ci = &get_instance();
        $ci->db->where("status", 1)->where("voucher_id", $voucher_id)->delete("tbl_vouchers");
        $ci->db->where("status", 1)->where("voucher_id", $voucher_id)->delete("tbl_voucherdetails");
    }
    function showVoucher($voucher_id)
    {
        $ci = &get_instance();
        $Voucher = $ci->db->where("status", 1)->where("voucher_id", $voucher_id)->get("tbl_vouchers")->row();
        $Voucher->Details = $ci->db->where("status", 1)->where("voucher_id", $voucher_id)->get("tbl_voucherdetails")->result();
        $Voucher->Type = $ci->db->where("status", 1)->where("vouchertype_id", $Voucher->voucher_type)->get("tbl_vouchertypes")->row();
    ?>
        <div class="card card-primary card-outline">
            <div class="card-header">
                <h5 class="m-0"><?php echo $Voucher->Type->voucher_type; ?> Voucher No. <?php echo $Voucher->voucher_no; ?> <a onclick="javascript:showPDF(<?php echo $voucher_id; ?>);//printDiv('printableDiv');" class="btn btn-primary btn-sm float-right">Print</a></h5>
            </div>
            <div class="card-body" id="printableDiv">
                <div class="row mt-5">
                    <div class="col">
                        <h3 class="text-center"><?php echo $ci->session->userdata("CompanyName"); ?></h3>
                    </div>
                </div>
                <div class="row mb-5">
                    <div class="col">
                        <h5 class="text-center"> <?php echo $Voucher->Type->voucher_type; ?> Voucher </h5>
                    </div>
                </div>
                <!-- <p class="text-right">Date (AD): <?php echo $Voucher->voucher_date; ?></p>
                <p class="text-right">Date (BS): <?php echo NepaliDate($Voucher->voucher_date); ?></p> -->
                <?php $TableData = $Voucher->Details; ?>
                <?php $TotalCols = 4; ?>
                <table class="table table-bordered ">
                    <thead>
                        <tr>
                            <!-- <th class="col-1"><?php myLang("Sn"); ?></th> -->
                            <th width="150px"><?php myLang("Date (B.S)"); ?></th>
                            <!-- <th class="col-1"><?php myLang("Date (A.D)"); ?></th> -->
                            <th><?php myLang("Account"); ?></th>
                            <!-- <th><?php //myLang("Narration"); 
                                        ?></th> -->
                            <th class="text-right" width="150px"><?php myLang("Debit"); ?></th>
                            <th class="text-right" width="150px"><?php myLang("Credit"); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $r = 0;
                        $drTotal = 0;
                        $crTotal = 0;
                        foreach ($TableData as $TableRow) : $r++; ?>
                            <?php foreach ($TableRow as $cols) : $id = $cols;
                                break;
                            endforeach; ?><tr>
                                <!-- <td><?php echo $r; ?></td> -->
                                <td><?php echo NepaliDate($TableRow->transaction_date); ?></td>
                                <!-- <td><?php echo $TableRow->transaction_date; ?></td> -->
                                <td><?php echo getFieldfromValue("tbl_accounts", "account_name", "account_id", $TableRow->account_id); ?></td>
                                <!-- <td><?php //echo $TableRow->narration; 
                                            ?></td> -->
                                <td><?php echo myCurrency($TableRow->dr);
                                    $drTotal += $TableRow->dr; ?></td>
                                <td><?php echo myCurrency($TableRow->cr);
                                    $crTotal += $TableRow->cr; ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php while ($r < 15) : ?>
                            <tr>
                                <?php for ($i = 0; $i < $TotalCols; $i++) : ?>
                                    <td>&nbsp;</td>
                                <?php endfor; ?>
                            </tr>
                        <?php $r++;
                        endwhile; ?>
                    <tbody>
                    <tfoot>
                        <tr>
                            <td colspan="<?php echo $TotalCols - 2; ?>" class="text-right text-bold">Total</td>
                            <td><?php echo myCurrency($drTotal); ?></td>
                            <td><?php echo myCurrency($drTotal); ?></td>
                        </tr>
                        <tr>
                            <td colspan="<?php echo $TotalCols; ?>" class="text-left" height=100>Narration: <?php echo $TableRow->narration; ?></td>
                        </tr>
                        <tr>
                            <td colspan="<?php echo $TotalCols; ?>" class="text-center" height=200>
                                <div class="row mt-100">
                                    <div class="col-2"><span class="underline-text"><?php echo $Voucher->created_by; ?></span></div>
                                    <div class="col-2 offset-3">______________</div>
                                    <div class="col-2 offset-3">______________</div>
                                </div>
                                <div class="row">
                                    <div class="col-2">Entered By</div>
                                    <div class="col-2 offset-3">Checked By</div>
                                    <div class="col-2 offset-3">Approved By</div>
                                </div>
                            </td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
        </div>
    <?php
    }
    function showAccountsCombo($fieldName, $displayName, $fieldID, $condition = "", $default = "", $CSSclass = "")
    {
        $ci = &get_instance();
    ?>
        <?php if ($displayName != "") : ?>
            <label for="<?php echo $fieldID; ?>"><?php echo function_exists("myLang") ? myLang($displayName) : $displayName; ?></label>
        <?php endif; ?>
        <select name="<?php echo $fieldName; ?>" class="form-control select2 <?php echo $CSSclass; ?>" id="<?php echo $fieldID; ?>">
            <option value="">Select <?php echo function_exists("myLang") ? myLang($displayName) : $displayName; ?></option>
            <?php
            $q = "select *,(select accategory_name from tbl_accategories where tbl_accategories.accategory_id=tbl_accounts.accategory_id) as accategory_name from tbl_accounts";
            $q .= ($condition != "") ? " where $condition" : " where status=1";
            $q .= " order by accategory_id, account_name";
            //  echo $q;
            $Values = $ci->db->query($q)->result();
            $current_category = "";
            foreach ($Values as $value) : ?>
                <?php if ($current_category != $value->accategory_name) : ?>
                    <optgroup label="<?php echo $value->accategory_name; ?>">
                    <?php endif; ?>
                    <option value="<?php echo $value->account_id; ?>" <?php echo ($value->account_id == $default) ? 'SELECTED' : ''; ?>>
                        <?php echo $value->accategory_name; ?> >>
                        <?php echo $value->account_name; ?>
                    </option>
                    <?php if ($current_category != $value->accategory_name) : ?>
                    </optgroup>;
                <?php $current_category = $value->accategory_name;
                    endif; ?>
            <?php endforeach; ?>
        </select>
    <?php
    }
    function showAccountsComboForVoucher($fieldName, $displayName, $fieldID, $condition = "", $default = "", $CSSclass = "", $defaultCategories = array())
    {
        $ci = &get_instance();
    ?>
        <?php if ($displayName != "") : ?>
            <label for="<?php echo $fieldID; ?>"><?php echo function_exists("myLang") ? myLang($displayName) : $displayName; ?></label>
        <?php endif; ?>
        <select name="<?php echo $fieldName; ?>" class="form-control select2 <?php echo $CSSclass; ?>" id="<?php echo $fieldID; ?>">
            <option value="">Select <?php echo function_exists("myLang") ? myLang($displayName) : $displayName; ?></option>
            <?php
            $q = "select *,(select accategory_name from tbl_accategories where tbl_accategories.accategory_id=tbl_accounts.accategory_id) as accategory_name from tbl_accounts";
            $q .= ($condition != "") ? " where $condition" : " where status=1";
            $q .= " order by accategory_id, account_name";
            //  echo $q;
            $Values = $ci->db->query($q)->result();
            $current_category = "";
            foreach ($Values as $value) : ?>
                <?php if (!empty($defaultCategories)) : ?>
                    <?php if (in_array($value->accategory_id, $defaultCategories)) : ?>
                        <option value="<?php echo $value->account_id; ?>" <?php echo ($value->account_id == $default) ? 'SELECTED' : ''; ?>>
                            <?php echo $value->accategory_name; ?> >>
                            <?php echo $value->account_name; ?>
                        </option>
                    <?php endif; ?>
                <?php else : ?>
                    <option value="<?php echo $value->account_id; ?>" <?php echo ($value->account_id == $default) ? 'SELECTED' : ''; ?>>
                        <?php echo $value->accategory_name; ?> >>
                        <?php echo $value->account_name; ?>
                    </option>
                <?php endif; ?>
            <?php endforeach; ?>
           
        </select>
        <button type="button" class="btn input-group-text addplus" data-toggle="modal" data-target="#exampleModal"><i class="fas fa-plus"></i></button>
                
        
      
        
    <?php
    }
    function showAccountsCategoriesCombo($fieldName, $displayName, $fieldID, $condition = "", $default = "", $CSSclass = "")
    {
        $ci = &get_instance();
    ?>
        <?php if ($displayName != "") : ?>
            <label for="<?php echo $fieldID; ?>"><?php echo function_exists("myLang") ? myLang($displayName) : $displayName; ?></label>
        <?php endif; ?>
        <select name="<?php echo $fieldName; ?>" class="form-control select2 <?php echo $CSSclass; ?>" id="<?php echo $fieldID; ?>">
            <option value="">Select </option>
            <!-- <option value="">Select <?php //echo function_exists("myLang") ? myLang($displayName) : $displayName; ?></option> -->
            <?php
            $q = "select *,(select acgroup_name from tbl_acgroups where tbl_accategories.acgroup_id=tbl_acgroups.acgroup_id) as acgroup_name from tbl_accategories";
            $q .= ($condition != "") ? " where $condition" : " where status=1";
            $q .= " order by accategory_name";
            // echo $q;
            $Values = $ci->db->query($q)->result();
            $current_acgroup = "";
            /*
            foreach ($Values as $value) : ?>
                <?php if ($current_acgroup != $value->acgroup_name) : ?>
                    <optgroup label="<?php echo $value->acgroup_name; ?>">
                    <?php endif; ?>
                    <option value="<?php echo $value->accategory_id; ?>" <?php echo ($value->accategory_id == $default) ? 'SELECTED' : ''; ?>>
                        <?php echo $value->acgroup_name; ?> >>
                        <?php echo $value->accategory_name; ?>
                    </option>
                    <?php if ($current_acgroup != $value->acgroup_name) : ?>
                    </optgroup>;
            <?php $current_acgroup = $value->acgroup_name;
                    endif;
                endforeach;

                */
            foreach ($Values as $value) : ?>


                <option value="<?php echo $value->accategory_id; ?>" <?php echo ($value->accategory_id == $default) ? 'SELECTED' : ''; ?>>

                    <?php echo $value->accategory_name; ?>
                </option>

            <?php
            endforeach;
            ?>
        </select>
        
    <?php
    }
    function showFixedAccountsCategoriesCombo($fieldName, $displayName, $fieldID, $condition = "", $default = "", $CSSclass = "")
    {
        $ci = &get_instance();
    ?>
        <?php if ($displayName != "") : ?>
            <label for="<?php echo $fieldID; ?>"><?php echo function_exists("myLang") ? myLang($displayName) : $displayName; ?></label>
        <?php endif; ?>
        <select name="<?php echo $fieldName; ?>" class="form-control select2 <?php echo $CSSclass; ?>" id="<?php echo $fieldID; ?>">
            <option value="">Select </option>
            <!-- <option value="">Select <?php //echo function_exists("myLang") ? myLang($displayName) : $displayName; ?></option> -->
            <?php
            $q = "select *,(select acgroup_name from tbl_acgroups where tbl_accategories.acgroup_id=tbl_acgroups.acgroup_id) as acgroup_name from tbl_accategories";
            $q .= ($condition != "") ? " where $condition" : " where status=1";
            $q .= " and parent_category_id=0";
            $q .= " order by accategory_name";
            // echo $q;
            $Values = $ci->db->query($q)->result();
            $current_acgroup = "";
            /*
            foreach ($Values as $value) : ?>
                <?php if ($current_acgroup != $value->acgroup_name) : ?>
                    <optgroup label="<?php echo $value->acgroup_name; ?>">
                    <?php endif; ?>
                    <option value="<?php echo $value->accategory_id; ?>" <?php echo ($value->accategory_id == $default) ? 'SELECTED' : ''; ?>>
                        <?php echo $value->acgroup_name; ?> >>
                        <?php echo $value->accategory_name; ?>
                    </option>
                    <?php if ($current_acgroup != $value->acgroup_name) : ?>
                    </optgroup>;
            <?php $current_acgroup = $value->acgroup_name;
                    endif;
                endforeach;

                */
            foreach ($Values as $value) : ?>


                <option value="<?php echo $value->accategory_id; ?>" <?php echo ($value->accategory_id == $default) ? 'SELECTED' : ''; ?>>

                    <?php echo $value->accategory_name; ?>
                </option>

            <?php
            endforeach;
            ?>
        </select>
        
    <?php
    }
    function showAccountsCategoriesWithParentsCombo($fieldName, $displayName, $fieldID, $condition = "", $default = "", $CSSclass = "", $extras = "")
    {
        $ci = &get_instance();
    ?>
        <?php if ($displayName != "") : ?>
            <label for="<?php echo $fieldID; ?>"><?php echo function_exists("myLang") ? myLang($displayName) : $displayName; ?></label>
        <?php endif; ?>
        <select name="<?php echo $fieldName; ?>" class="form-control select2 <?php echo $CSSclass; ?>" id="<?php echo $fieldID; ?>" <?php echo $extras; ?>>
            <option value="">Select </option>
            <?php
            $q = "select *,(select acgroup_name from tbl_acgroups where tbl_accategories.acgroup_id=tbl_acgroups.acgroup_id) as acgroup_name from tbl_accategories";
            $q .= ($condition != "") ? " where $condition" : " where status=1";
            $q .= " order by accategory_name";
            //echo $q;
            $Values = $ci->db->query($q)->result();
            $current_acgroup = "";
            foreach ($Values as $value) : ?>
                <?php if ($current_acgroup != $value->acgroup_name) : ?>
                    <!--optgroup label="<?php echo $value->acgroup_name; ?>"-->
                    <?php endif; ?>
                    <option value="<?php echo $value->accategory_id; ?>" <?php echo ($value->accategory_id == $default) ? 'SELECTED' : ''; ?>><?php echo $value->accategory_name; ?></option>
                    <?php if ($current_acgroup != $value->acgroup_name) : ?><!--/optgroup-->
                <?php $current_acgroup = $value->acgroup_name;
                    endif; ?>
            <?php endforeach; ?>
        </select>
<?php
    }
    private function getVoucherAmount($voucher_id)
    {
        $ci = &get_instance();
        $t = "select sum(dr) as amount from tbl_voucherdetails where voucher_id='$voucher_id'";
        $Transaction = $ci->db->query($t)->row();
        return $Transaction->amount;
    }
    private function getVoucherTransactions($voucher_id)
    {
        $ci = &get_instance();
        $t = "select *,(select account_name from tbl_accounts where tbl_accounts.account_id=tbl_voucherdetails.account_id) as account_name from tbl_voucherdetails where voucher_id='$voucher_id'";
        $Transactions = $ci->db->query($t)->result();
        return $Transactions;
    }
    public function getAccountCategories()
    {
        $ci = &get_instance();
        $t = "select * from tbl_accategories as b where status=1";
        $AccountCategories = $ci->db->query($t)->result();
        foreach ($AccountCategories as $AccountCategory) :
            $AccountCategory->AccountGroup = $ci->db->query("select * from tbl_acgroups where acgroup_id = '$AccountCategory->acgroup_id'")->row();
            if ($AccountCategory->parent_category_id <> 0) {
                $AccountCategory->Parent = $ci->db->query("select * from tbl_accategories where accategory_id = '$AccountCategory->parent_category_id'")->row();
            }
        endforeach;
        return $AccountCategories;
    }
    //NEW METHODS
    function getAccountBalanceR($BalanceBy, $ReferenceValue, &$ACBalances = array())
    {
        $ci = &get_instance();
        if ($BalanceBy == "Account") {
            $account_id = $ReferenceValue;
            $t = "SELECT * FROM tbl_voucherdetails WHERE account_id = '$account_id' AND status <> -1";
            // echo $t;die;
            $Vouchers = $ci->db->query($t)->result();
            $DrBalance = 0;
            $CrBalance = 0;
            foreach ($Vouchers as $Voucher) {
                $DrBalance += $Voucher->dr;
                $CrBalance += $Voucher->cr;
            }
            $ACBalances['DrBalance'] = $DrBalance;
            $ACBalances['CrBalance'] = $CrBalance;
            $ACBalances['Balance'] = $DrBalance - $CrBalance;
            return $ACBalances['Balance'];
        }
        if ($BalanceBy == "Group") {
            $accategory_id = $ReferenceValue;
            $t = "SELECT * FROM tbl_accounts WHERE accategory_id = '$accategory_id'";
            $Accounts = $ci->db->query($t)->result();
            $groupBalance = 0;
            foreach ($Accounts as $Account) {
                $groupBalance += $this->getAccountBalanceR("Account", $Account->account_id, $ACBalances);
            }
            return $groupBalance;
        }
        if ($BalanceBy == "Category") {
            $accategory_id = $ReferenceValue;
            $t = "SELECT * FROM tbl_accategories WHERE parent_category_id = '$accategory_id'";
            $Categories = $ci->db->query($t)->result();
            $categoryBalance = 0;
            foreach ($Categories as $Category) {
                $categoryBalance += $this->getAccountBalanceR("Account", $Category->accategory_id, $ACBalances);
            }
            return $categoryBalance;
        }
        if ($BalanceBy == "Types") {
            $acgroup_id = $ReferenceValue;
            $t = "SELECT * FROM tbl_accategories WHERE  acgroup_id = '$acgroup_id'";
            $Categories = $ci->db->query($t)->result();
            $typesBalance = 0;
            foreach ($Categories as $Category) {
                $typesBalance += $this->getAccountBalanceR("Group", $Category->accategory_id, $ACBalances);
            }
            return $typesBalance;
        }
        return 0;
    }
    function backupDatabase()
    {
        $ci = &get_instance();
        $ci->load->database();
        $dumpFilePath = __DIR__ . '/../../backup/' . $ci->db->database . '-backup-' . date('y-m-d-h-i-s') . '.sql';
        $Filename = $ci->db->database . '-backup-' . date('y-m-d-h-i-s') . '.sql';
        $command = "mysqldump -u " . $ci->db->username . " -p" . $ci->db->password . " -h " . $ci->db->hostname . " " . $ci->db->database . " > $dumpFilePath";
        $output = shell_exec($command);
        if ($output === null) {
            // echo "Database dump successful. File saved at: $Filename";
            mail("prajwalbro@gmail.com", "Account Database Backup", "Database dump successful. File saved at: $Filename");
        } else {
            echo "Error: Database dump failed. Please check your configuration and try again.";
        }
    }
    function initDatabase()
    {
        $ci = &get_instance();
        $ci->load->database();
        $ci->load->dbforge();
        if (!$ci->db->table_exists('tbl_vouchertypes')) {
            return; // Table doesn't exist, no need to proceed
        }
        $fields = $ci->db->list_fields('tbl_vouchertypes');
        // Check if 'default_credits' column exists
        if (!in_array('default_credits', $fields)) {
            $ci->dbforge->add_column('tbl_vouchertypes', array('default_credits' => array('type' => 'VARCHAR', 'constraint' => 255)));
        }
        // Check if 'default_debits' column exists
        if (!in_array('default_debits', $fields)) {
            $ci->dbforge->add_column('tbl_vouchertypes', array('default_debits' => array('type' => 'VARCHAR', 'constraint' => 255)));
        }
    }

    function hasTransaction($type, $id)
    {
        switch ($type) {
            case 'fiscalyear':
                $ci = &get_instance();
                $transactions = $ci->db->where("fiscalyear_id", $id)->get("tbl_voucherdetails");
                // pre($transactions);die;
                if ($transactions->num_rows() > 0) {
                    return true;
                } else {
                    return false;
                }
                break;
            case 'branch':
                $ci = &get_instance();
                $transactions = $ci->db->where("branch_id", $id)->get("tbl_voucherdetails");
                // pre($transactions);die;
                if ($transactions->num_rows() > 0) {
                    return true;
                } else {
                    return false;
                }
                break;
            case 'accategory':
                $ci = &get_instance();
                $t = "select * from tbl_voucherdetails where account_id in (select account_id from tbl_accounts where accategory_id=$id) or account_id in (select account_id from tbl_accounts where accategory_id in (select accategory_id from tbl_accategories where parent_category_id=$id))";
                $transactions = $ci->db->query($t);
                // pre($transactions);die;
                if ($transactions->num_rows() > 0) {
                    return true;
                } else {
                    return false;
                }
                break;
            case 'account':
                $ci = &get_instance();
                $t = "select * from tbl_voucherdetails where voucher_id<>0 and  account_id =$id";
                $transactions = $ci->db->query($t);
                // pre($transactions);die;
                if ($transactions->num_rows() > 0) {
                    return true;
                } else {
                    return false;
                }
                break;
            case 'units':
                $ci = &get_instance();
                $t = "select * from tbl_items where units_id=$id";
                $transactions = $ci->db->query($t);
                // pre($transactions);die;
                if ($transactions->num_rows() > 0) {
                    return true;
                } else {
                    return false;
                }
                break;
            case 'itemcategory':
                $ci = &get_instance();
                $t = "select * from tbl_items where itemcategories_id=$id";
                $transactions = $ci->db->query($t);
                // pre($transactions);die;
                if ($transactions->num_rows() > 0) {
                    return true;
                } else {
                    return false;
                }
                break;
            case 'items':
                $ci = &get_instance();
                $t = "select * from tbl_items where item_id in (select items_id from tbl_salesdetails where items_id=$id) or item_id in (select item_id from tbl_purchasedetails where items_id=$id)";
                // echo $t;die;
                $transactions = $ci->db->query($t);
                // pre($transactions);die;
                if ($transactions->num_rows() > 0) {
                    return true;
                } else {
                    return false;
                }
                break;
            default:
                return false;
        }
    }
}