<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Vouchers extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->helper("accounts");
        $this->load->library("myaccounts");
        checkLogin();
    }
    public function _remap($alias = "", $params = array())
    {

        $data['dataValue'] = $this->session;
        $data['pageTitle'] = "Accounting Vouchers";
        switch ($alias) {
            case 'print':
                $voucher_id = $this->uri->segment(4);
                $VoucherPDF = $this->myaccounts->voucherPDF($voucher_id);
                $data['PDFFile'] = site_url("pdf/vouchers/" . $VoucherPDF);
                if (isset($_GET['modal']))
                    $this->load->view("accounts/pdfviewer", $data);
                else
                    loadView("accounts/pdfviewer", $data);
                break;
            case 'listvouchers':
                $data['pageTitle'] = "Vouchers";
                $fromDate_bs = isset($_GET['from_date']) ? $_GET['from_date'] : firstDayOfNepaliMonth();
                $todate_bs = isset($_GET['to_date']) ? $_GET['to_date'] : NepaliDate(Today());
                $fromDate_ad = NepaliToEnglishDate($fromDate_bs);
                $toDate_ad = NepaliToEnglishDate($todate_bs);
                $data['fromDate_bs'] = $fromDate_bs;
                $data['toDate_bs'] = $todate_bs;
                $data['fromDate_ad'] = $fromDate_ad;
                $data['toDate_ad'] = $toDate_ad;
                $data['VoucherTypes']=$this->myaccounts->getVoucherTypes();
                loadView("accounts/vouchers/listvouchers", $data);
                break;
            case 'addvoucher':
                $data['pageTitle'] = "Journal Voucher";
                if (isset($_POST['submit']) && !isVoucherExists($_POST['voucher_no'])) {
                    $TableData = array(
                        'voucher_no' => filter_var($_POST['voucher_no']),
                        'voucher_ref' => "JV" . filter_var($_POST['voucher_no']), // If the voucher is raised against other transactions
                        'voucher_date' => NepaliToEnglishDate(filter_var($_POST['voucher_date'])),
                        'voucher_state' => 'Entered',  // Different stages of voucher Entered/Reversed/Cancel/Deleted/Locked/Draft etc.
                        'voucher_type' => 'Journal',  //Different types of Vouchers like Cash/Bank/Payment/Receipt/advance etc.
                        'fiscalyear_id' => $this->session->userdata("FiscalYearID"),
                        'branch_id' => $this->session->userdata("BranchID"),
                        'created_by' => $this->session->userdata("loggedUser"),
                        'created_on' => date('Y-m-d H:i:s'),
                        'remarks' => filter_var($_POST['remarks']),
                        'status' => 1
                    );
                    $this->db->insert('tbl_vouchers', $TableData);
                    $voucher_id = $this->db->insert_id();
                    $account_ids = $_POST['account_ids'];
                    $narrations = $_POST['narration'];
                    $debits = $_POST['debit'];
                    $credits = $_POST['credit'];
                    $entry_no = 0;
                    for ($entry_no = 0; $entry_no < sizeof($account_ids); $entry_no++) {
                        $TableData = array();
                        $TableData = array(
                            'voucher_id' => $voucher_id,
                            'entry_no' => $entry_no,
                            'transaction_date' => NepaliToEnglishDate(filter_var($_POST['voucher_date'])),
                            'account_id' => $account_ids[$entry_no],
                            'narration' => $narrations[$entry_no],
                            'dr' => $debits[$entry_no],
                            'cr' => $credits[$entry_no],
                            //    'cheque' => filter_var($_POST['cheque']),
                            //    'cheque_details' => filter_var($_POST['cheque_details']),
                            'currency' => 'NPR',
                            //    'exrate' => filter_var($_POST['exrate']),
                            //    'fcdr' => filter_var($_POST['fcdr']),
                            //    'fccr' => filter_var($_POST['fccr']),
                            'branch_id' => $this->session->userdata("BranchID"),
                            'fiscalyear_id' => $this->session->userdata("FiscalYearID"),
                            'created_on' => date('Y-m-d H:i:s'),
                            'created_by' => $this->session->userdata("loggedUser"),
                            //    'remarks' => filter_var($_POST['remarks']),
                            'status' => 1
                        );
                        $this->db->insert('tbl_voucherdetails', $TableData);
                    }
                    redirect("accounts/vouchers/print/" . $voucher_id);
                    break;
                }

                loadView("accounts/vouchers/addvoucher", $data);
                break;
            case 'voucherdetails':
                $voucher_id = $this->uri->segment(4);
                $Voucher = $this->db->where("voucher_id", $voucher_id)->get("tbl_vouchers")->row();
                $Voucher->Details = $this->db->where("voucher_id", $voucher_id)->get("tbl_voucherdetails")->result();
                $data['Voucher'] = $Voucher;
                $this->load->view("accounts/vouchers/voucherdetails", $data);
                break;
            case 'show_voucher':
                $data['pageTitle'] = "Voucher Entries";
                $voucher_id = $this->uri->segment(4);
                $Voucher = $this->db->where("voucher_id", $voucher_id)->get("tbl_vouchers")->row();
                if($Voucher) {
                $Voucher->Details = $this->db->where("voucher_id", $voucher_id)->get("tbl_voucherdetails")->result();
                $data['Voucher'] = $Voucher;
                $data['voucher_id'] = $voucher_id;
                loadview("accounts/vouchers/show_voucher", $data);
                }
                break;
            case 'reversal':
                $voucher_id = $this->uri->segment(4);
                if (isVoucherReverseable($voucher_id)) :
                    $VoucherDetails = $this->db->where("voucher_id", $voucher_id)->get("tbl_voucherdetails")->result();
                    $entry_no = 0;
                    foreach ($VoucherDetails as $VoucherDetail) :
                        $TableData = array(
                            'voucher_id' => $voucher_id,
                            'entry_no' => $entry_no,
                            'transaction_date' => $VoucherDetail->transaction_date,
                            'account_id' => $VoucherDetail->account_id,
                            'narration' => "Reversal of Voucher #" . getFieldfromValue("tbl_vouchers", "voucher_no", "voucher_id", $VoucherDetail->voucher_id),
                            'dr' => $VoucherDetail->cr,
                            'cr' => $VoucherDetail->dr,
                            //    'cheque' => filter_var($_POST['cheque']),
                            //    'cheque_details' => filter_var($_POST['cheque_details']),
                            'currency' => 'NPR',
                            //    'exrate' => filter_var($_POST['exrate']),
                            //    'fcdr' => filter_var($_POST['fcdr']),
                            //    'fccr' => filter_var($_POST['fccr']),
                            'branch_id' => $this->session->userdata("BranchID"),
                            'fiscalyear_id' => $this->session->userdata("FiscalYearID"),
                            'created_on' => date('Y-m-d H:i:s'),
                            'created_by' => $this->session->userdata("loggedUser"),
                            //    'remarks' => filter_var($_POST['remarks']),
                            'status' => 1
                        );
                        $this->db->insert('tbl_voucherdetails', $TableData);
                        $entry_no++;
                    endforeach;
                    $this->db->where("voucher_id", $voucher_id)->set("voucher_state", 'Reversed')->update("tbl_vouchers");
                endif;
                redirect("accounts/vouchers/listvouchers");
                break;

            case 'saveaccount':
                if (isset($_POST['submit'])) {
                    if (!$this->checkifAccountExists($_POST['account_name'])) {
                        $TableData = array(
                            'accategory_id' => filter_var($_POST['accategory_id']),
                            //   'account_code' => generateAccountCode(filter_var($_POST['account_code'])),
                            'account_name' => filter_var($_POST['account_name']),
                            // 'account_type' => filter_var($_POST['account_type']),
                            // 'account_plcategory' => filter_var($_POST['account_plcategory']),
                            // 'account_currency' => filter_var($_POST['account_currency']),
                            // 'account_partyname' => filter_var($_POST['account_partyname']),
                            // 'account_partyaddress' => filter_var($_POST['account_partyaddress']),
                            // 'account_partypan' => filter_var($_POST['account_partypan']),
                            // 'account_partycontact' => filter_var($_POST['account_partycontact']),
                            // 'account_partyemail' => filter_var($_POST['account_partyemail']),
                            // 'account_partycontactperson' => filter_var($_POST['account_partycontactperson']),
                            // 'account_partycontactpersoncontact' => filter_var($_POST['account_partycontactpersoncontact']),
                            'created_on' => date('Y-m-d H:i:s'),
                            'created_by' => 'admin',
                            'remarks' => filter_var($_POST['remarks']),
                            'status' => 1,
                        );
                        $this->db->insert('tbl_accounts', $TableData);
                        $account_id = $this->db->insert_id();
                        $voucherData = array(
                            "voucher_id" => 0,
                            "transaction_date" => date("Y-m-d"),
                            "account_id" => $account_id,
                            "Dr" => 0,
                            "Cr" => 0,
                            "fiscalyear_id" => $this->session->userdata['FiscalYearID'],
                            "created_on" => date('Y-m-d H:i:s'),
                            "branch_id" => $this->session->userdata("BranchID"),
                            "created_by" => $this->session->userdata("loggedUser"),
                            "remarks" => "Opening Balance Entry",
                            "status" => 1
                        );
                        if ($_POST['opening_balance_drcr'] == "DR") $voucherData['Dr'] = $_POST['opening_balance'];
                        if ($_POST['opening_balance_drcr'] == "CR") $voucherData['Cr'] = $_POST['opening_balance'];
                        $this->db->insert('tbl_voucherdetails', $voucherData);
                        redirect("accounts/accountheads/list");
                    } else {
                        echo "Account Head Name Already Exists";
                        die;
                    }
                }
                loadView("accounts/accountheads/add", $data);
                break;


            default:
                if ($VoucherType = $this->myaccounts->getVoucherType($alias)) {
                    $this->processVoucher($VoucherType);
                    break;
                }
                loadView("accounts/vouchers/listvouchers", $data);
        }
    }
    private function processVoucher($VoucherType)
    {
        $data['pageTitle'] = $VoucherType->voucher_name;
        $data['VoucherType'] = $VoucherType;
        $command = $this->uri->segment(4);
        switch ($command) {
            case 'create':
                $voucher_no = generateVoucherNo($VoucherType->vouchertype_id);
                if (isset($_POST['submit'])) {
                    $TableData = array(
                        'voucher_no' => $voucher_no,
                        'voucher_ref' => $VoucherType->vouchertype_id,
                        'voucher_date' => NepaliToEnglishDate(filter_var($_POST['voucher_date'])),
                        'voucher_state' => 'Entered',  // Different stages of voucher Entered/Reversed/Cancel/Deleted/Locked/Draft etc.
                        'voucher_type' => $VoucherType->vouchertype_id,  //Different types of Vouchers like Cash/Bank/Payment/Receipt/advance etc.
                        'fiscalyear_id' => $this->session->userdata("FiscalYearID"),
                        'branch_id' => $this->session->userdata("BranchID"),
                        'created_by' => $this->session->userdata("loggedUser"),
                        'created_on' => date('Y-m-d H:i:s'),
                        // 'remarks' => filter_var($_POST['remarks']),
                        'status' => 1
                    );
                    $this->db->insert('tbl_vouchers', $TableData);
                    $voucher_id = $this->db->insert_id();
                    $account_ids = $_POST['account_ids'];
                    $narration = $_POST['narration'];
                    $debits = $_POST['debit'];
                    $credits = $_POST['credit'];
                    $entry_no = 0;
                    $entryTotal = 0;
                    for ($entry_no = 0; $entry_no < sizeof($account_ids); $entry_no++) {
                        $TableData = array();
                        $entryTotal += $debits[$entry_no];
                        $TableData = array(
                            'voucher_id' => $voucher_id,
                            'entry_no' => $entry_no,
                            'transaction_date' => NepaliToEnglishDate(filter_var($_POST['voucher_date'])),
                            'account_id' => $account_ids[$entry_no],
                            'narration' => $narration,
                            'dr' => $debits[$entry_no],
                            'cr' => $credits[$entry_no],
                            // 'cheque' => isset($_POST['cheque_number']) ? $_POST['cheque_number'][$entry_no] : "",
                            // 'cheque_details' => isset($_POST['cheque_details']) ? $_POST['cheque_details'][$entry_no] : "",
                            'currency' => 'NPR',
                            //    'exrate' => filter_var($_POST['exrate']),
                            //    'fcdr' => filter_var($_POST['fcdr']),
                            //    'fccr' => filter_var($_POST['fccr']),
                            'branch_id' => $this->session->userdata("BranchID"),
                            'fiscalyear_id' => $this->session->userdata("FiscalYearID"),
                            'created_on' => date('Y-m-d H:i:s'),
                            'created_by' => $this->session->userdata("loggedUser"),
                            //    'remarks' => filter_var($_POST['remarks']),
                            'status' => 1
                        );
                        //pre($TableData);die;
                        $this->db->insert('tbl_voucherdetails', $TableData);
                    }
                    $entry_no++;


                    echo json_encode(['status' => 'success']);
                    break;
                }

                loadview("accounts/vouchers/create", $data);
                // loadview("accounts/vouchers/$VoucherType->voucher_alias/create", $data);
                break;
            default:
                // $dirname = getcwd() . "/application/views/accounts/vouchers/$VoucherType->voucher_alias";
                // $filename = $dirname . "/create.php";
                // //echo getcwd() . "\n";die;
                // if (!file_exists($filename)) {
                //     mkdir($dirname, 0777);
                //     $this->createView($filename);
                //     $filename = $dirname . "/list.php";
                //     $this->createListView($filename);
                // }



                $data['Vouchers'] = $this->db->where("status", 1)->where("voucher_type", $VoucherType->vouchertype_id)->get("tbl_vouchers")->result();

                // echo '<pre>' . $VoucherType->vouchertype_id;
                // print_r($VoucherType);
                // die();

                // loadview("accounts/vouchers/$VoucherType->voucher_alias/list", $data);
                redirect("accounts/vouchers/listvouchers?vouchertypes=".$VoucherType->vouchertype_id);
        }
    }
    private function createView($filename)
    {
        $CreateFileContent = "<div class=\"content-wrapper\">\n
    <div class=\"content-header\">\n
        <div class=\"container-fluid\">\n
            <div class=\"row mb-2\">\n
                <div class=\"col-sm-6\">\n
                    <h1 class=\"m-0\">\n<?php echo \$pageTitle; ?></h1>
                </div>
                <div class=\"col-sm-6\">\n
                    <ol class=\"breadcrumb float-sm-right\">\n
                        <li class=\"breadcrumb-item\">\n<a href=\"<?php echo base_url(); ?>\">\nDashboard</a></li>
                        <li class=\"breadcrumb-item active\">\n<?php echo \$pageTitle; ?></li>
                    </ol>
                </div>
            </div>
        </div>
    </div>
    <div class=\"content\">\n
        <div class=\"container-fluid\">\n
            <div class=\"row\">\n
                <div class=\"col\">\n
                    <div class=\"card card-primary card-outline\">\n
                        <div class=\"card-header\">\n
                            <h5 class=\"m-0\">\nCreate <?php echo \$pageTitle; ?> </h5>
                        </div>
                        <div class=\"card-body\">\n
                            <?php if(\$VoucherType->voucher_options==\"\"): ?>
                            <form method=POST action=\"\" enctype=\"multipart/form-data\" name=\"tbl_accounts\">\n
                                <div class=\"row\">\n
                                    <div class=\"col-3\">\n
                                        <fieldset>
                                            <legend>Transaction Date</legend><input type=\"text\" class=\"form-control nepaliDatePicker\" id=\"voucher_date\" value=\"<?php echo NepaliDate(); ?>\" name=\"voucher_date\">\n
                                        </fieldset>
                                    </div>
                                    <div class=\"col-3\">\n
                                        <fieldset>
                                            <?php \$DefaultAccount=\$this->myaccounts->getAccountDetails(\$VoucherType->default_account);?>
                                            <legend><?php  echo \$DefaultAccount->account_name; ?> Balance</legend><?php  echo myCurrency(\$DefaultAccount->Balance); ?>
                                        </fieldset>
                                    </div>
                                    <div class=\"col-3 offset-3\">\n
                                        <fieldset>
                                            <legend>Voucher #</legend><input type=\"text\" readonly class=\"form-control\" id=\"voucher_no\" value=\"<?php echo generateVoucherNo(); ?>\" name=\"voucher_no\">\n
                                        </fieldset>
                                    </div>
                                </div>
                                <div class=\"row\">\n
                                    <div class=\"col\">\n
                                        <fieldset>
                                            <legend>Enter Transaction</legend>
                                            <table id=\"EntryTable\" class=\"table order-list\">\n
                                                <thead>
                                                    <tr>
                                                        <td>Account</td>
                                                        <td>Narration</td>
                                                        <td>Amount</td>
                                                        <td></td>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                        <td class=\"col-3\">\n <?php fillComboWithValue(\"account_id\", \"\", \"account_id\", \"tbl_accounts\", \"account_name\", \"account_id\", \"\", \"\", \"\", \"status=1\"); ?> </td>
                                                        <td class=\"col-4\">\n <input type=\"text\" name=\"narration\" id=\"narration\" class=\"form-control\" /> </td>
                                                        <td class=\"col-1\">\n <input type=\"text\" name=\"debit\" id=\"debit\" value=\"0\" class=\"form-control\" /> </td>
                                                        <td class=\"col-1\">\n <input type=\"button\" class=\"btn btn-primary full-width\" id=\"addrow\" value=\"Add\" /> </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                            <div id=\"errorBox\" class=\"alert alert-secondary hidden\" role=\"alert\">\n
                                                <h5></h5>
                                            </div>
                                        </fieldset>
                                        <div class=\"card card-primary card-outline\">\n
                                            <div class=\"card-header\">\nTransaction List </div>
                                            <div class=\"card-body\">\n
                                                <table id=\"myTable\" class=\" table order-list table-striped table-bordered\">\n
                                                    <thead>
                                                        <tr>
                                                            <td>Account</td>
                                                            <td>Narration</td>
                                                            <td>Amount</td>
                                                        </tr>
                                                    </thead>
                                                    <tbody> </tbody>
                                                    <tfoot>
                                                        <tr>
                                                            <th colspan=\"2\" class=\"text-right\">\nTotal</th>
                                                            <td>
                                                                <div id=\"debitTotal\">\n</div>
                                                            </td>
                                                            <td>
                                                               
                                                            </td>
                                                        </tr>
                                                    </tfoot>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class=\"row\">\n
                                    <!--COL START-->
                                    <div class=\"col\">\n
                                        <div class=\"form-group\">\n <label for=\"remarks\">\nRemarks</label> <textarea class=\"form-control\" id=\"remarks\" name=\"remarks\">\n</textarea> </div>
                                    </div>
                                    <!--COL END-->
                                </div> <button class=\"btn btn-primary\" type=\"submit\" id=\"saveButton\" name=\"submit\">\nSave Voucher</button>
                            </form>
                            <?php else: ?>
                                <?php echo \$VoucherType->voucher_options; ?>
                                <?php endif; ?>

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    \$(document).ready(function() {
        var counter = 0;
        \$(\"#addrow\").on(\"click\", function() {
            var msg = \"Transaction Row Added !!\";
            if (\$(\"#account_id\").val() != \"\") {
                if (!isAccountAdded(\$(\"#account_id\").val())) {
                    if (\$(\"#narration\").val() != \"\") {
                        var debit = (\$.isNumeric(\$(\"#debit\").val()) ? \$(\"#debit\").val() : 0);
                        if (\$.isNumeric(debit)) {
                            if (debit > 0) {
                                addRow()
                            } else {
                                msg = \"Amount contain some value\";
                            }
                        } else {
                            msg = \"Non numberic value entered in amount. \";
                        }
                    } else {
                        msg = \"Narration can't be empty!\";
                    }
                } else {
                    msg = \"Account already added in transactions\";
                }
            } else {
                msg = \"Account Head Not Selected!\";
            }
            \$(\"#errorBox h5\").html(msg);
            \$(\"#errorBox\").fadeTo(2000, 500).slideUp(500, function() {
                \$(\"#errorBox\").slideUp(500);
            });
        });
        \$(\"table.order-list\").on(\"click\", \".ibtnDel\", function(event) {
            \$(this).closest(\"tr\").remove();
            calculateTotals();
        });
    });

    function isAccountAdded(account_id) {
        var arr = \$('input[name=\"account_id[]\"]').map(function() {
            return this.value;
        }).get();
        if (\$.inArray(account_id, arr) >= 0) return true;
        else return false;
    }

    function addRow() {
        var newRow = \$(\"<tr>\");
        var cols = \"\";
        cols += '<td><input type=\"hidden\" class=\"form-control\" name=\"account_ids[]\" value=\"' + \$(\"#account_id\").val() + '\"/><input type=\"text\" readonly class=\"form-control\" name=\"account_name[]\" value=\"' + \$(\"#account_id option:selected\").text() + '\"/></td>';
        cols += '<td><input type=\"text\" readonly class=\"form-control\" name=\"narration[]\" value=\"' + \$(\"#narration\").val() + '\"/></td>';
        cols += '<td><input type=\"text\" readonly class=\"form-control\" name=\"debit[]\" value=\"' + (\$.isNumeric(\$(\"#debit\").val()) ? \$(\"#debit\").val() : 0) + '\"/></td>';
        cols += '<td><input type=\"button\" class=\"ibtnDel btn btn-md btn-danger \"  value=\"Delete\"></td>';
        newRow.append(cols);
        \$(\"#myTable.order-list\").append(newRow);
        calculateTotals();
    }

    function calculateTotals() {
        var debitTotal = 0;
        var creditTotal = 0;
        var balance = 0;
        \$(\"table.order-list\").find('input[name^=\"debit[]\"]').each(function() {
            debitTotal += +\$(this).val();
        });
        \$(\"#debit\").val(0);
        \$(\"#narration\").val(\"\");
        \$(\"#debitTotal\").text(debitTotal.toFixed(2));
        \$(\"#balance\").text(balance.toFixed(2));
        \$(\"#saveButton\").prop(\"disabled\", false);        
    }
    \$(\"#saveButton\").prop(\"disabled\", true);
</script>";
        file_put_contents($filename, $CreateFileContent);
    }
    private function createListView($filename)
    {
        $ListFileContent = "<div class=\"content-wrapper\">\n
<div class=\"content-header\">\n
    <div class=\"container-fluid\">\n
        <div class=\"row mb-2\">\n
            <div class=\"col-sm-6\">\n

                <h1 class=\"m-0\">\n<?php echo \$pageTitle; ?></h1>
            </div>
            <div class=\"col-sm-6\">\n
                <ol class=\"breadcrumb float-sm-right\">\n

                    <li class=\"breadcrumb-item\">\n<a href=\"<?php echo base_url(); ?>\">\nDashboard</a></li>
                    <li class=\"breadcrumb-item active\">\n<?php echo \$pageTitle; ?></li>

                </ol>
            </div>
        </div>
    </div>
</div>
<div class=\"content\">\n
    <div class=\"container-fluid\">\n
        <div class=\"row\">\n
            <div class=\"col\">\n

                <div class=\"card card-primary card-outline\">\n
                    <div class=\"card-header\">\n

                        <h5 class=\"m-0\">\n<?php echo \$pageTitle; ?> <a href=\"<?php echo site_url(\"accounts/vouchers/\".\$VoucherType->voucher_alias.\"/create\"); ?>\" class=\"btn btn-sm btn-primary float-right\">\nCreate New <?php echo \$pageTitle; ?></a></h5>

                    </div>

                    <div class=\"card-body\">\n

                        <?php \$TableData = \$Vouchers ?>

                        <table class=\"table table-bordered table-striped\" id=\"voucherList\">\n
                            <thead>
                                <tr>
                                    <th>ID#</th>
                                    <th>Voucher No</th>
                                    <th>Voucher Date</th>

                                    <th>Voucher Type</th>
                                    <th>Voucher State</th>

                                    <th class=\"table-col col-2\">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach (\$TableData as \$TableRow) : ?>
                                    <?php foreach (\$TableRow as \$cols) : \$id = \$cols;
                                        break;
                                    endforeach; ?><tr data-id=\"<?php echo \$TableRow->voucher_id; ?>\" class=\"<?php echo(\$TableRow->voucher_state==\"Reversed\")?\"table-danger\":\"\"; ?>\">\n
                                        <td><?php echo \$TableRow->voucher_id; ?></td>
                                        <td><?php echo \$TableRow->voucher_no; ?></td>

                                        <td><?php echo \$TableRow->voucher_date; ?></td>

                                        <td><?php echo \$TableRow->voucher_type; ?></td>
                                        <td><?php echo \$TableRow->voucher_state; ?></td>

                                        <td class=\"col-1\">\n
                                            <a onClick=\"javascript:showDetails(<?php echo \$id; ?>);\" class=\"btn btn-success btn-xs\" title=\"View Details\">\n<i class=\"fa fa-eye\">\n</i></a>

                                        </td>
                                    </tr>

                                <?php endforeach; ?>
                            <tbody>
                        </table>
                        <div class=\"modal fade\" id=\"voucherdetails_box\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"voucherdetails_box\" aria-hidden=\"true\">\n
                            <div class=\"modal-dialog modal-xl\" role=\"document\">\n
                                <div class=\"modal-content\">\n
                                    <div class=\"modal-header\">\n
                                        <h5 class=\"modal-title\" id=\"exampleModalLabel\">\nVoucher Details</h5>
                                        <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\">\n
                                            <span aria-hidden=\"true\">\n&times;</span>
                                        </button>
                                    </div>
                                    <div class=\"modal-body\" id=\"details_container\">\n
                                        Voucher Details Goes Here
                                    </div>
                                    <div class=\"modal-footer\">\n
                                        <button type=\"button\" onClick='reversalEntry()' id=\"reversalBtn\" class=\"btn btn-secondary\" data-dismiss=\"modal\" data-id=\"\">\nRevarsal Entry</button>
                                        <button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\">\nClose</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <script>
                            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>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>
<?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);
    }
</script>
<?php
}
?>";
        file_put_contents($filename, $ListFileContent);
    }
    function checkifAccountExists($account_name)
    {
        return ($this->db->query("select * from tbl_accounts where UPPER(account_name)='" . strtoupper($account_name) . "'")->num_rows() > 0) ? true : false;
    }
}