<?php
require_once __DIR__ . '/vendor/autoload.php';

if (isset($_POST['action'])) {
    $_SESSION['image-file']   = $_POST['image-file'];
    $_SESSION['mcount']       = json_decode($_POST['mcount'], true);
    $_SESSION['actual_slope'] = $_POST['actual_slope'];

    $filename = UPLOAD_DIR . DIRECTORY_SEPARATOR . "{$_SESSION['uuid']}.png";
    base64StringToPng($_POST['image-file'], $filename);
}

if (isset($_POST['action'])) {
    header('Location: save.php');
    exit;
}
?><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Builder - QRAMP Ramp Builder</title>

    <link rel="stylesheet" href="css/tachyons.css?v3">
    <link rel="stylesheet" href="css/styles.css?v3">
    <link rel="stylesheet" href="css/builder.o.css?v3">

</head>

<body<?= !empty($_SESSION['ada_compliant']) ? ' class="ada-mode"' : '' ?>>

<?php if (defined('DEBUG') && DEBUG) {
echo '<details><summary>Session Data</summary><pre>' . print_r($_SESSION, true) . '</pre></details>';
echo '<details><summary>Post Data</summary><pre>' . print_r($_POST, true) . '</pre></details>';
} ?>
    <header>
        <div id="guidance-message" class="blue bg-light-blue ba pa2 ma2 fw5 tc">
            <span id="guidance-text">Begin with an entry module — Mod 6 is most commonly used for transitioning from the doorway to the ramp system.</span>
        </div>

        <div class="flex justify-between gh5 items-center lh-copy ph3">
            <a href="https://qramp.com" target="_blank" title="Visit the QRamp website">
                <img src="images/qramp-logo.png" alt="QRamp - Modular Access System" width="230" height="90">
            </a>

            <div class="tc nowrap">
                <span class="f6">For assistance please call</span><br>
                <a class="f3 fw5" href="tel:+18556977267">(855)-697-7267</a>
            </div>
        </div>

        <nav class="flex flex-wrap gv2 gh3 pa3 tc justify-between">
            <div class="flex gv2 gh3 f6">
                <a href="/index.php">
                    <img src="images/toolbar/home.png" class="pen" alt="" width="50" height="50"><br>
                    Home
                </a>

                <form style="display:none" id="saveQuoteForm" action="builder.php" method="post">
                    <input type="hidden" id="action" name="action" value="save">
                    <input type="hidden" id="image-file" name="image-file">
                    <input type="hidden" id="mcount" name="mcount">
                    <input type="hidden" id="actual_slope" name="actual_slope">

                    <button class="reset blue pointer" name="save" id="save" type="submit">
                        <img src="images/toolbar/save.png" class="pen" alt="" width="50" height="50"><br>
                        Save & Continue
                    </button>
                </form>

                <button class="reset blue pointer" id="undo" onclick="removeLastModule()" title="Remove the previously added module.">
                    <img src="images/toolbar/undo.svg" class="pen" alt="" width="50" height="50"><br>
                    Undo
                </button>
            </div>

            <div class="flex gv2 gh3 f6">
                <a href="https://qramp.com/find-a-dealer" title="Find a Dealer (opens a new window)" target="_blank">
                    <img src="images/toolbar/search.png" on alt="" width="50" height="50"><br>
                    Find a Dealer
                </a>
            </div>

            <div class="flex gv2 gh3 f6">
                <button class="reset blue pointer" id="icon-dimension-horizontal">
                    <img src="images/toolbar/measure-w.png" class="pen" alt="" width="50" height="50"><br>
                    Measure Width
                </button>

                <button class="reset blue pointer" id="icon-dimension-vertical">
                    <img src="images/toolbar/measure-l.png" class="pen" alt="" width="50" height="50"><br>
                    Measure Length
                </button>

                <button class="reset blue pointer" id="icon-tutorial" onclick="openTutorialModal()">
                    <img src="images/toolbar/video.svg" class="pen" alt="" width="50" height="50"><br>
                    Tutorial
                </button>
            </div>
        </nav>

        <div id="tutorial-modal" class="fixed top-0 left-0 w-100 h-100 z-9999 flex items-center justify-center" style="display:none!important;background:rgba(0,0,0,0.7);">
            <div class="bg-white shadow-2 pa3 relative" style="width:min(90vw,800px);">
                <button class="reset absolute top-0 right-0 pa2 f4 lh-solid pointer blue fw5" onclick="closeTutorialModal()" title="Close">&times;</button>
                <div style="position:relative;padding-bottom:56.25%;height:0;overflow:hidden;">
                    <iframe id="tutorial-iframe" src="" allow="accelerometer;autoplay;clipboard-write;encrypted-media;gyroscope;picture-in-picture" allowfullscreen style="position:absolute;top:0;left:0;width:100%;height:100%;border:0;"></iframe>
                </div>
            </div>
        </div>

        <div id="tabs" style="display: none;" class="bg-light-gray"></div>

        <div id="ramp-complete-banner" class="dn tc pa4 bg-lightest-blue bt bw2 b--blue">
            <p class="f3 fw6 blue mt0 mb2">Your Ramp is Complete.</p>
            <p class="f5 mb3 mid-gray">You can now save and download a PDF of your design &nbsp;<button class="f5 fw5 ph3 pv2 bg-blue white bn br2 pointer dim" onclick="document.getElementById('save').click()">Save and Continue</button></p>
        </div>
    </header>

    <div class="info-box ba b--blue fixed right-1 bottom-1 w5 z-999 bg-white">
        <span class="db bg-blue white pa2 flex justify-between items-center">
            <span>Info</span>
            <button class="reset white pointer f5 lh-solid" onclick="toggleInfoBoxSide()" title="Move to other side">&#8644;</button>
        </span>
        <table class="w-100 pv1 ph2">
            <tr class="blue">
                <th width="30px"></th>
                <th align="right">Target</th>
                <th align="right">Actual</th>
            </tr>
            <tr>
                <th align="right">Rise</th>
                <td align="right"><?= $_SESSION['rise']; ?>in</td>
                <td align="right"><span id="actual-rise"></span></td>
            </tr>
            <tr>
                <th align="right">Slope</th>
                <td align="right">1:<?= $_SESSION['target_slope']; ?></td>
                <td align="right"><span id="actual-slope"></span></td>
            </tr>
        </table>
        <span class="db tc pa2 bg-light-gray" id="slope-info"></span>
        <?php if ( $_SESSION['target_rise'] >= 32 ) : ?>
        <div id="extended-legs-notice" class="bg-lightest-blue blue pa2 fw5 bt b--blue f6">
            <span class="db f6 mb1 ttu tracked blue">Notice</span>
            Your target rise of <strong><?= $_SESSION['target_rise'] ?>&Prime;</strong> requires <strong>Extended Legs</strong>.
        </div>
        <?php endif; ?>
    </div>

    <div id="totalLengthWarning" class="dark-red bg-washed-red pv2 ph3 ma2 fw5 tc dn">
        When the ramp length reaches 30 feet, a resting platform is required to comply with building codes.
        <?php if (!empty($_SESSION['ada_compliant'])): ?>
        For ADA compliant ramps, use <strong>Mod 8</strong> or <strong>Mod 10</strong> only.
        <?php else: ?>
        Use <strong>Mod 3</strong>, <strong>Mod 8</strong>, <strong>Mod 9</strong>, or <strong>Mod 10</strong>.
        <?php endif; ?>
    </div>

    <div id="container"></div>

    <div id="dialog-message">
        <p>Please wait while we build your ramp...</p>
    </div>

    <script>const adaCompliant = <?= !empty($_SESSION['ada_compliant']) ? 'true' : 'false' ?>;</script>
    <script src="js/konva.min.js?v3"></script>
    <script src="js/modules.js?v3"></script>
    <script src="js/compatibility.js?v3"></script>

    <script src="js/init.js?v3"></script>

    <script src="js/directions.js?v3"></script>
    <script src="js/adjustments.js?v3"></script>
    <script src="js/main.js?v3"></script>
    <script src="js/functions.js?v3"></script>

    <script>
        function updateInfoBox() {
            var countM1 = 0;
            var countM2 = 0;
            var countM7B = 0;

            var Mod1  = ["Module1N", "Module1S", "Module1W", "Module1E"];
            var Mod2  = ["Module2N", "Module2W"];
            var Mod7B = ["Module7BN", "Module7BS", "Module7BW", "Module7BE"];

            for (var i = 0; i < modules.length; i++) {
                mod_name = modules[i].name();
                if (Mod1.indexOf(mod_name)  > -1) countM1  += 1;
                if (Mod2.indexOf(mod_name)  > -1) countM2  += 1;
                if (Mod7B.indexOf(mod_name) > -1) countM7B += 1;
            }

            let modCount   = Number(countM1) + Number(countM2);
            let mod7Count  = Number(countM7B);
            let currentRise = Number(<?= $_SESSION['rise']; ?>);
            let targetSlope = Number(<?= $_SESSION['target_slope']; ?>);

            var actualSlopeEl = document.getElementById('actual-slope');
            var slopeInfoEl   = document.getElementById('slope-info');

            var actualRiseEl = document.getElementById('actual-rise');

            if (modCount === 0 && mod7Count === 0) {
                actualRiseEl.innerHTML  = '';
                actualSlopeEl.innerHTML = '';
                slopeInfoEl.innerHTML   = '';
                return;
            }

            actualRiseEl.innerHTML = currentRise + 'in';

            actualSlope = ((modCount * 4 * 12) + (mod7Count * 12)) / currentRise;
            actualSlope = actualSlope.toFixed(1);

            actualSlopeEl.innerHTML   = '1:' + actualSlope;
            actualSlopeEl.style.color = 'red';

            if ((targetSlope - actualSlope) <= 1 && (targetSlope - actualSlope) >= -1) {
                actualSlopeEl.style.color = 'green';
                slopeInfoEl.innerHTML     = 'Target Slope Achieved!';
                slopeInfoEl.style.color   = 'green';
            } else {
                actualSlopeEl.style.color = 'red';
                slopeInfoEl.innerHTML     = '';
            }
        }

        function toggleInfoBoxSide() {
            let box    = document.querySelector('.info-box');
            let notice = document.getElementById('extended-legs-notice');
            if (box.classList.contains('right-1')) {
                box.classList.replace('right-1', 'left-1');
                if (notice) notice.classList.replace('left-1', 'right-1');
            } else {
                box.classList.replace('left-1', 'right-1');
                if (notice) notice.classList.replace('right-1', 'left-1');
            }
        }

        function openTutorialModal() {
            var modal = document.getElementById('tutorial-modal');
            document.getElementById('tutorial-iframe').src = 'https://www.youtube.com/embed/SbxtGHugCa8?autoplay=1';
            modal.style.setProperty('display', 'flex', 'important');
        }

        function closeTutorialModal() {
            var modal = document.getElementById('tutorial-modal');
            document.getElementById('tutorial-iframe').src = '';
            modal.style.setProperty('display', 'none', 'important');
        }

        document.addEventListener('DOMContentLoaded', function () {
            document.getElementById('tutorial-modal').addEventListener('click', function (e) {
                if (e.target === this) closeTutorialModal();
            });
            document.addEventListener('keydown', function (e) {
                if (e.key === 'Escape') closeTutorialModal();
            });

            var tip = document.createElement('div');
            tip.className = 'mod-tooltip';
            document.body.appendChild(tip);

            document.querySelectorAll('#tabs ul li[data-tooltip]').forEach(function (li) {
                li.addEventListener('mouseenter', function () {
                    var r = this.getBoundingClientRect();
                    tip.textContent = this.dataset.tooltip;
                    tip.style.left = r.left + 'px';
                    tip.style.top = (r.bottom + 4) + 'px';
                    tip.hidden = false;
                });
                li.addEventListener('mouseleave', function () {
                    tip.hidden = true;
                });
            });
        });
    </script>

</body>
</html>
