<?php
require_once('includes/load.php');
page_require_level(3);

if (isset($_GET['id'])) {
    $sale_id = (int)$_GET['id'];
    $sale = find_sale_by_id($sale_id);

    if (!$sale) {
        $session->msg("d", "Sale not found!");
        redirect('sales.php');
    }
} else {
    $session->msg("d", "Missing sale ID.");
    redirect('sales.php');
}

if (isset($_POST['update_sale'])) {
    $req_fields = array('qty');
    validate_fields($req_fields);

    if (empty($errors)) {
        $qty = (int)$_POST['qty'];

        $sql = "UPDATE sales SET qty = '{$qty}' WHERE id = '{$sale_id}'";
        $result = $db->query($sql);

        if ($result) {
            $session->msg("s", "Sale updated.");
            redirect('sales.php');
        } else {
            $session->msg("d", "Sale update failed.");
            redirect('edit_sale.php?id=' . $sale_id);
        }
    } else {
        $session->msg("d", $errors);
        redirect('edit_sale.php?id=' . $sale_id);
    }
}

include_once('layouts/header.php');
?>

<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
    </div>
</div>

<div class="row">
    <div class="col-md-6">
        <div class="panel panel-default">
            <div class="panel-heading">
                <strong>
                    <span class="glyphicon glyphicon-th"></span>
                    Edit Sale
                </strong>
            </div>
            <div class="panel-body">
                <form method="post" action="edit_sale.php?id=<?php echo $sale_id; ?>" class="clearfix">
                    <div class="form-group">
                        <label for="qty">Quantity</label>
                        <input type="number" class="form-control" name="qty" value="<?php echo (int)$sale['qty']; ?>">
                    </div>
                    <div class="form-group">
                        <button type="submit" name="update_sale" class="btn btn-primary">Update Sale</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include_once('layouts/footer.php'); ?>
