<?php
/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
$register = [
    "name" => lang("no cash", false),
    "id" => ""
];

$registeropen = false;
if (isset($_SESSION['register'])) {
    $registeropen = $database->has("registers", ['[>]cash_drawer' => ['registerid' => 'registerid']], ['AND' => ['open[!]' => null, 'close' => null, 'registers.registerid' => $_SESSION['register']]]);
}

if (isset($_GET['switch']) || !isset($_SESSION['register']) || !$registeropen) {
    require_once __DIR__ . "/../lib/chooseregister.php";
} else {
    $register = $database->get('registers', ['registerid (id)', 'registername (name)'], ['registerid' => $_SESSION['register']]);
    $showgridbydefault = $binstack->count('items', ['AND' => ['price[!]' => null, 'price[!]' => 0]]) <= GRID_BY_DEFAULT_MAX_ITEMS;
    $items = [];
    $payments = [];
    $editing = false;
    $returning = false;
    if (isset($VARS['txid']) && $database->has('transactions', ['txid' => $VARS['txid']])) {
        $tx = $database->get('transactions', ['[>]customers' => 'customerid'], ['txid', 'discountpercent', 'transactions.customerid', 'customers.name (customername)', 'cashid', 'type'], ['txid' => $VARS['txid']]);
        if ($tx['type'] != 1) {
            header('Location: app.php?page=pos&msg=return_transaction_no_edit');
            die();
        }
        $items = $database->select('lines', ['lineid', 'amount', 'name', 'itemid', 'qty'], ['txid' => $tx['txid']]);
        if ($database->has('cash_drawer', ['AND' => ['cashid' => $tx['cashid'], 'open[!]' => null, 'close' => null]])) {
            $editing = true;
            $payments = $database->select('payments', ['[>]certificates' => 'certid', '[>]payment_types' => ['type' => 'typeid']], ['payments.amount', 'typename', 'icon', 'text', 'certcode'], ['txid' => $tx['txid']]);
            echo "<input type=\"hidden\" id=\"txid\" value=\"$tx[txid]\">";
            echo "<input type=\"hidden\" id=\"edit_customerid\" value=\"$tx[customerid]\">";
        } else {
            $returning = true;
            echo "<input type=\"hidden\" id=\"return\" value=\"1\">";
        }
    }
    ?>
    <div class="modal fade" tabindex="-1" role="dialog" id="receiptmodal">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-receipt"></i> <?php lang("receipt"); ?></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="display-4 text-center" id="receiptchangediv"><?php lang("change"); ?>: $<span id="receiptchange">0.00</span></div>
                    <iframe class="w-100 shadow-lg" id="receiptframe"></iframe>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php lang("close"); ?></button>
                    <button type="button" class="btn btn-primary" id="receiptprintbtn"><i class="fas fa-print"></i> <?php lang("print"); ?></button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" tabindex="-1" role="dialog" id="customermodal">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-user"></i> <?php lang("customer"); ?></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="input-group">
                        <input type="text" class="form-control" id="customersearch" placeholder="<?php lang("customer search"); ?>" />
                        <div class="input-group-append">
                            <button class="btn btn-link" type="button" id="customersearchbtn"><i class="fas fa-search"></i></button>
                        </div>
                    </div>
                    <div class="list-group mt-2" id="customerselection">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php lang("close"); ?></button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" tabindex="-1" role="dialog" id="managermodal">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-cog"></i> <?php lang("register management"); ?></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-12 col-md-6">
                            <div class="input-group">
                                <input type="text" class="form-control" id="transactionsearch" placeholder="<?php lang("transaction search"); ?>" />
                                <div class="input-group-append">
                                    <span class="btn btn-link open-number-pad-btn">
                                        <i class="fas fa-keyboard"></i>
                                    </span>
                                    <span class="btn btn-link" id="txsearch-datetime-btn">
                                        <span class="fa-layers fa-fw">
                                            <i class="fas fa-calendar" data-fa-transform="shrink-3 up-4 left-4"></i>
                                            <i class="fas fa-clock" data-fa-transform="shrink-3 down-4 right-4"></i>
                                        </span>
                                    </span>
                                    <button class="btn btn-link" type="button" id="transactionsearchbtn"><i class="fas fa-search"></i></button>
                                </div>
                            </div>

                            <div class="row d-none" id="txsearch-datetimefilters">
                                <div class="input-group col-md-6">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text"><i class="fas fa-play"></i></span>
                                    </div>
                                    <input type="text" class="form-control" id="tx-startdate" data-toggle="datetimepicker" data-target="#tx-startdate" />
                                </div>
                                <div class="input-group col-md-6">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text"><i class="fas fa-stop"></i></span>
                                    </div>
                                    <input type="text" class="form-control" id="tx-enddate" data-toggle="datetimepicker" data-target="#tx-enddate" />
                                </div>
                            </div>
                            <div class="list-group mt-2" id="transactionselection">
                            </div>
                        </div>
                        <div class="col-12 col-md-6">
                            <div class="d-flex justify-content-between flex-wrap">
                                <button type="button" class="btn btn-default" id="opendrawerbtn"><i class="fas fa-lock-open"></i> <?php lang("open drawer"); ?></button>
                                <button type="button" class="btn btn-primary ml-auto" id="xprintbtn"><i class="fas fa-print"></i> <?php lang("print"); ?></button>
                            </div>
                            <iframe class="w-100 shadow-lg" id="xframe" src="action.php?action=xreport&format=html&register=<?php echo $register['id']; ?>"></iframe>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php lang("close"); ?></button>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-12 col-md-6 order-1 order-md-0">
            <div class="card d-flex">
                <div class="card-header p-1">
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <span class="btn btn-default" id="gridviewbtn" title="<?php lang("grid view"); ?>"><i class="fas fa-th fa-fw"></i></span>
                        </div>
                        <?php
                        if (isset($_SESSION['mobile'])) {
                            ?>
                            <div class="input-group-prepend">
                                <span class="btn btn-default" onclick="scancode('#barcode'); mobilecode = true;">
                                    <i class="fas fa-barcode fa-fw"></i>
                                </span>
                            </div>
                        <?php } ?>
                        <input type="text" class="form-control" id="barcode" placeholder="<?php lang("barcode or search"); ?>" />
                        <div class="input-group-append">
                            <button class="btn btn-link" type="button" id="barcodebtn"><i class="fas fa-search"></i></button>
                        </div>
                    </div>
                </div>
                <div class="d-none justify-content-around flex-wrap" id="gridview">

                </div>
                <div>
                    <div class="list-group list-group-flush" id="pos-lines-box">
                        <?php
                        foreach ($items as $i) {
                            $linetotal = $i['amount'] * $i['qty'];
                            $amount = $i['amount'];
                            // Include percentage discount for returns
                            if ($returning) {
                                $linetotal *= 1.0 - ($tx['discountpercent'] / 100.0);
                                $amount *= 1.0 - ($tx['discountpercent'] / 100);
                            }
                            ?>
                            <div class="list-group-item" data-itemid="<?php echo $i['itemid']; ?>">
                                <div class="d-flex w-100 justify-content-between mb-2">
                                    <h5 class="item-name"><?php echo $i['name']; ?></h5>
                                    <h5>
                                        <span class="badge badge-light">
                                            $<span class="line-total"><?php echo number_format($linetotal, 2); ?></span>
                                        </span>
                                    </h5>
                                </div>
                                <div class="d-inline-flex">
                                    <div class="input-group qty-control">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text pr-1"><b>$</b></span>
                                        </div>
                                        <input type="money" class="form-control item-price" value="<?php echo number_format($amount, 2); ?>"/>
                                        <div class="input-group-append">
                                            <span class="btn btn-outline-primary open-number-pad-btn">
                                                <i class="fas fa-keyboard"></i>
                                            </span>
                                        </div>
                                        <div class="input-group-prepend">
                                            <span class="input-group-text px-2"><i class="fas fa-times"></i></span>
                                            <button class="btn btn-red qty-minus" type="button"><i class="fas <?php
                                                if ($i['qty'] > 1) {
                                                    echo "fa-minus";
                                                } else {
                                                    echo "fa-trash";
                                                }
                                                ?>"></i></button>
                                        </div>
                                        <input type="number" class="form-control item-qty px-2" value="<?php echo $i['qty']; ?>" />
                                        <div class="input-group-append">
                                            <button class="btn btn-light-green qty-plus" type="button"><i class="fas fa-plus"></i></button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php
                        }
                        ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-12 col-md-6 order-0 order-md-1">
            <div class="card mb-3 mb-md-0">
                <div class="w-100 position-absolute d-flex align-items-start px-3 pt-2">
                    <a href="#" class="mr-auto text-body" id="openmanagement" data-toggle="tooltip" title="<?php lang("manage register") ?>"><i class="fas fa-cog"></i> <?php lang("manage"); ?></a>
                    <a href="app.php?page=pos&switch" class="ml-auto text-body" id="register" data-id="<?php echo $register['id']; ?>" data-toggle="tooltip" title="<?php lang("change register") ?>"><i class="fas fa-exchange-alt"></i> <?php echo $register['name']; ?></a>
                </div>
                <div class="display-4 p-1 p-md-3 text-center">$<span id="grand-total">0.00</span></div>
                <div class="card-body d-flex justify-content-center flex-wrap py-0 my-0">
                    <div class="btn m-1" id="addcustomerbtn">
                        <i class="fas fa-user-circle"></i>
                        <span id="customerbtnlabel"><?php
                            if ($editing && isset($tx['customername'])) {
                                echo $tx['customername'];
                            }
                            ?></span>
                        <span class="sr-only"><?php lang("customer"); ?></span>
                    </div>
                    <?php
                    if (!$returning) {
                        ?>
                        <div class="btn m-1" id="discountpercentbtn" data-percent="<?php
                        if ($editing && isset($tx['discountpercent']) && $tx['discountpercent'] != 0) {
                            echo (float) $tx['discountpercent'];
                        } else {
                            echo "0";
                        }
                        ?>">
                            <span id="discountpercentbtnlabel"><?php
                                if ($editing && isset($tx['discountpercent']) && $tx['discountpercent'] != 0) {
                                    echo (float) $tx['discountpercent'];
                                }
                                ?></span>
                            <i class="fas fa-percent"></i>
                            <span class="sr-only"><?php lang("transaction discount"); ?></span>
                        </div>
                        <?php
                    }
                    ?>
                    <div class="btn m-1" id="deletetxbtn">
                        <i class="fas fa-trash"></i>
                        <span class="sr-only"><?php lang("delete transaction"); ?></span>
                    </div>
                </div>

                <div class="card-body d-md-none">
                    <span class="btn btn-green btn-lg btn-block" id="paymentbtn"><i class="fas fa-money-bill-wave"></i> <?php
                        if ($returning) {
                            lang("enter refund");
                        } else {
                            lang("enter payment");
                        }
                        ?></span>
                </div>

                <div id="paymentui" class="d-none d-md-block">
                    <div class="card-body">
                        <div class="d-flex justify-content-around flex-wrap">
                            <?php
                            $payment_methods = $database->select('payment_types', ['typeid (id)', 'typename (name)', 'icon', 'text']);
                            $hideforreturns = ['check', 'free'];
                            foreach ($payment_methods as $data) {
                                if ($returning && in_array($data['name'], $hideforreturns)) {
                                    continue;
                                }
                                ?>
                                <div class="card p-2 text-center m-1 payment-method-button" data-payment-method="<?php echo $data['name']; ?>" data-icon="<?php echo $data['icon']; ?>" data-text="<?php lang($data['text']); ?>">
                                    <i class="<?php echo $data['icon']; ?> fa-3x fa-fw"></i>
                                    <?php lang($data['text']); ?>
                                </div>
                                <?php
                            }
                            ?>
                        </div>
                    </div>
                    <hr />
                    <div class="row px-2 mb-3 text-center">
                        <?php
                        if ($returning) {
                            ?>
                            <div class="col-12 col-sm-4">
                                <?php lang("refund"); ?> $<span id="paid-amount">0.00</span>
                            </div>
                            <div class="col-12 col-sm-4">
                                <?php lang("owed"); ?> $<span id="owed-amount">0.00</span>
                            </div>
                            <div class="col-12 col-sm-4">
                                <?php lang("change"); ?> $<span id="change-amount">0.00</span>
                            </div>
                            <?php
                        } else {
                            ?>
                            <div class="col-12 col-sm-4">
                                <?php lang("paid"); ?> $<span id="paid-amount">0.00</span>
                            </div>
                            <div class="col-12 col-sm-4">
                                <?php lang("owed"); ?> $<span id="owed-amount">0.00</span>
                            </div>
                            <div class="col-12 col-sm-4">
                                <?php lang("change"); ?> $<span id="change-amount">0.00</span>
                            </div>
                            <?php
                        }
                        ?>
                    </div>
                    <div class="list-group list-group-flush" id="payment-lines">
                        <?php
                        if ($editing) {
                            foreach ($payments as $p) {
                                if ($p['amount'] <= 0) {
                                    continue;
                                }
                                ?>
                                <div class="list-group-item">
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text">
                                                <i class="<?php echo $p['icon']; ?> fa-fw mr-1"></i>
                                                <?php lang($p['text']); ?>
                                            </span>
                                        </div>
                                        <div class="input-group-prepend">
                                            <span class="input-group-text">
                                                $
                                            </span>
                                        </div>
                                        <input class="form-control payment-entry" type="money" data-type="<?php echo $p['typename']; ?>" value="<?php echo number_format($p['amount'], 2); ?>" />
                                        <div class="input-group-prepend input-group-append">
                                            <span class="btn btn-outline-success open-money-pad-btn">
                                                <i class="fas fa-calculator"></i>
                                            </span>
                                        </div>
                                        <?php
                                        if ($p['typename'] == 'giftcard') {
                                            ?>
                                            <div class="input-group-prepend input-group-append">
                                                <span class="input-group-text">
                                                    #
                                                </span>
                                            </div>
                                            <input class="form-control giftcard-number" type="number" value="<?php echo $p['certcode']; ?>" />
                                            <div class="input-group-prepend input-group-append">
                                                <span class="btn btn-outline-primary open-number-pad-btn" data-gc="1">
                                                    <i class="fas fa-keyboard"></i>
                                                </span>
                                            </div>
                                            <?php
                                        }
                                        ?>
                                        <div class="input-group-append">
                                            <span class="btn btn-outline-danger remove-payment-btn">
                                                <i class="fas fa-trash"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <?php
                            }
                        }
                        ?>
                        <!-- Payments go here -->
                    </div>

                    <div class="card-body">
                        <span class="btn btn-green btn-lg btn-block" id="finishbtn"><i class="fas fa-receipt"></i> <?php
                            if ($editing) {
                                lang("update");
                            } else if ($returning) {
                                lang("return");
                            } else {
                                lang("finish");
                            }
                            ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script nonce="<?php echo $SECURE_NONCE; ?>">
        var showgridbydefault = <?php echo $showgridbydefault === true && $editing !== true && $returning !== true ? "true" : "false" ?>;
    </script>
    <?php
}
?>