<?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/. */

require_once __DIR__ . '/../required.php';

redirectifnotloggedin();

$carddata = [
    'id' => '',
    'code' => '',
    'amount' => 0,
    'start' => 0
];

$editing = false;

if (!empty($VARS['id']) && !is_empty($VARS['id'])) {
    if ($database->has('certificates', ['certid' => $VARS['id']])) {
        $editing = true;
        $carddata = $database->get(
                'certificates', [
            'certid (id)',
            'certcode (code)',
            'amount',
            'start_amount (start)'
                ], [
            'certid' => $VARS['id']
        ]);
    } else {
        // customer id is invalid, redirect to a version of the page that won't
        // cause an error when pressing Save
        header('Location: app.php?page=editcertificate');
        die();
    }
}

if (!$editing) {
    // Generate gift certificate number
    do {
        $carddata['code'] = random_int(100000000000, 999999999999);
    } while ($database->has('certificates', ['certcode' => $carddata['code']]));
}
?>

<form role="form" action="action.php" method="POST">
    <div class="card border-green">
        <h3 class="card-header text-green">
            <?php
            if ($editing) {
                ?>
                <i class="fas fa-edit"></i> <?php lang2("editing card x", ['code' => htmlspecialchars($carddata['code'])]); ?>
                <?php
            } else {
                ?>
                <i class="fas fa-edit"></i> <?php lang("adding card"); ?>
                <?php
            }
            ?>
        </h3>
        <div class="card-body row">
            <div class="form-group col-sm-6">
                <label for="code"><i class="fas fa-hashtag"></i> <?php lang("card number"); ?></label>
                <input type="text" class="form-control" id="code" name="code" value="<?php echo htmlspecialchars($carddata['code']); ?>" />
            </div>
            <div class="form-group col-sm-6">
                <label for="balance"><i class="fas fa-balance-scale"></i> <?php lang("balance"); ?></label>
                <input type="money" class="form-control" id="balance" name="balance" value="<?php echo number_format($carddata['amount'], 2); ?>" />
            </div>
        </div>

        <input type="hidden" name="id" value="<?php echo $carddata['id']; ?>" />
        <input type="hidden" name="action" value="editcertificate" />
        <input type="hidden" name="source" value="certificates" />

        <div class="card-footer d-flex">
            <button type="submit" class="btn btn-success mr-auto"><i class="fas fa-save"></i> <?php lang("save"); ?></button>
        </div>
    </div>
</form>