<?php

include "../../classes/autoload.php";

$html = new html("EDIT QUOTE TERMS");

$app = new inner_app();
$app->quick_bar("/app/quotes/");
$app->app_start();

$record_id = $_GET['record_id'];
$res  = $db->query("terms", "SELECT * FROM terms WHERE record_id = '$record_id'");
$term = $res->fetch_assoc();

?>

<div class="column width_90 background_1 border_radius">
    <h1>EDIT QUOTE TERMS</h1>

    <input type="text" hidden name="record_id" id="record_id" value="<?php echo $term['record_id']; ?>">

    <div class="row column_gap_2 width_80">
        <div class="column width_50">
            <label>ORDER TYPE</label>
            <select name="order_type" id="order_type">
                <option></option>
                <option <?php if($term['order_type'] == 'SUPPLY') echo 'selected'; ?>>SUPPLY</option>
                <option <?php if($term['order_type'] == 'SUPPLY & INSTALL') echo 'selected'; ?>>SUPPLY & INSTALL</option>
                <option <?php if($term['order_type'] == 'SUPPLY & DELIVERY') echo 'selected'; ?>>SUPPLY & DELIVERY</option>
            </select>
        </div>
    </div>

    <div class="row column_gap_2 width_80">
        <div class="column width_100">
            <label>IMPORTANT NOTES</label>
            <textarea name="notes" id="notes" class="width_100" rows="10"><?php echo $term['notes']; ?></textarea>
        </div>
    </div>

    <div class="row column_gap_2 width_80">
        <div class="column width_100">
            <label>TERMS</label>
            <textarea name="terms" id="terms" class="width_100" rows="12"><?php echo $term['terms']; ?></textarea>
        </div>
    </div>

    <br>
    <button class="width_90" onclick="save('update_terms.php')">SAVE</button>
    <br>
</div>

<script>
    function save(url) {
        if (document.getElementById('order_type').value == '') {
            alert('Please select an order type');
            return;
        }

        let payload = {};
        document.querySelectorAll("input, select, textarea").forEach(el => {
            if (!el.name) return;
            payload[el.name] = el.value;
        });

        let form = document.createElement("form");
        form.method = "POST";
        form.action = url;

        for (let key in payload) {
            let input = document.createElement("input");
            input.type = "hidden";
            input.name = key;
            input.value = payload[key];
            form.appendChild(input);
        }

        document.body.appendChild(form);
        form.submit();
    }
</script>