<?php
require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../lib/auth.php';
require_once __DIR__ . '/../../../lib/csrf.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

requireLogin();

$pageTitle = 'Water Test Analysis';
$siteName  = 'Crop Monitor';

include __DIR__ . '/../../../layouts/header.php';
include __DIR__ . '/../../../layouts/navbar.php';
?>

<style>
    .btn-append {
        color: #495057;
        background-color: #e9ecef;
        border: 1px solid #ced4da;
    }
</style>

<div id="layoutSidenav">
    <div id="layoutSidenav_nav">
        <?php include __DIR__ . '/../../../layouts/sidebar.php'; ?>
    </div>
    <div id="layoutSidenav_content">
        <main>
            <div class="container-fluid px-4">
                <h1 class="mt-4"><?= htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8') ?></h1>
                <ol class="breadcrumb mb-4">
                    <li class="breadcrumb-item"><a href="/dashboard/dashboard.php">Dashboard</a></li>
                    <li class="breadcrumb-item active">Water Test Analysis</li>
                </ol>

                <div class="row">
                    <div class="container">
                        <h3>Water Test Details</h3>
                        <span class="text-danger small">* required fields.</span>

                        <?php include __DIR__ . '/../../../components/clientDetailsForm.php'; ?>

                        <form method="post" action="/controllers/waterTestSubmit.php" id="WatercsvForm" class="needs-validation" novalidate>
                            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(generateCsrfToken(), ENT_QUOTES, 'UTF-8') ?>">

                            <hr>
                            <div class="row">
                                <div class="col">
                                    <small class="form-text text-muted">Lab No</small>
                                    <input type="text" class="form-control form-control-sm" name="lab_no" id="lab_no" placeholder="Lab No">
                                </div>

                                <div class="col">
                                    <small class="form-text text-muted">Batch No</small>
                                    <input type="text" class="form-control form-control-sm" name="batch_no" id="batch_no" placeholder="Batch No">
                                </div>

                                <div class="col">
                                    <small class="form-text text-muted">Date Sampled</small>
                                    <input type="date" class="form-control form-control-sm" name="date_sampled" id="date_sampled" placeholder="Date Sampled">
                                </div>

                                <div class="col">
                                    <small class="form-text text-muted">Sample ID <span class="text-danger">*</span></small>
                                    <input type="text" class="form-control form-control-sm" name="sample_id" id="sample_id" placeholder="Sample Id" required>
                                </div>

                                <div class="col">
                                    <small class="form-text text-muted">Site ID</small>
                                    <input type="text" class="form-control form-control-sm" name="site_id" id="site_id" placeholder="Paddock Id">
                                </div>
                            </div>

                            <hr>
                            <label class="col"><b>Analysis Inputs</b></label>

                            <div class="row mt-2">
                                <div class="col-md-2">
                                    <small class="form-text text-muted">pH <span class="text-danger">*</span></small>
                                    <div class="input-group input-group-sm mb-3">
                                        <input type="text" class="form-control form-control-sm" name="ph" id="ph" placeholder="pH" required>
                                        <span class="input-group-text">pH</span>
                                    </div>
                                </div>

                                <div class="col-md-2">
                                    <small class="form-text text-muted">Conductivity</small>
                                    <div class="input-group input-group-sm mb-3">
                                        <input type="text" class="form-control form-control-sm" name="cond_dsm" id="cond_dsm" placeholder="Conductivity">
                                        <span class="input-group-text">dS/m</span>
                                    </div>
                                </div>

                                <div class="col-md-2">
                                    <small class="form-text text-muted">Bicarbonate (HCO3-)</small>
                                    <div class="input-group input-group-sm mb-3">
                                        <input type="text" class="form-control form-control-sm" name="hco3" id="hco3" placeholder="HCO3-">
                                        <span class="input-group-text">mg/L</span>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <?php
                                $elements = [
                                    ['n',  'Nitrogen',   10000],
                                    ['p',  'Phosphorus', 10000],
                                    ['k',  'Potassium',  10000],
                                    ['s',  'Sulphur',    10000],
                                    ['mg', 'Magnesium',  10000],
                                    ['ca', 'Calcium',    10000],
                                ];
                                foreach ($elements as [$id, $label, $factor]): ?>
                                <div class="col-md-2">
                                    <small class="form-text text-muted"><?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?></small>
                                    <div class="input-group input-group-sm mb-3">
                                        <input type="text" class="form-control form-control-sm"
                                               name="<?= $id ?>" id="<?= $id ?>"
                                               placeholder="<?= htmlspecialchars($id . ' - ' . $label, ENT_QUOTES, 'UTF-8') ?>">
                                        <input class="btn btn-append" type="button"
                                               id="btn_<?= $id ?>" value="ppm"
                                               onclick="conversion(this, document.getElementById('<?= $id ?>'), <?= $factor ?>)">
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>

                            <div class="row">
                                <?php
                                $elements2 = [
                                    ['na', 'Sodium',    10000],
                                    ['fe', 'Iron',      10000],
                                    ['mn', 'Manganese', 10000],
                                    ['zn', 'Zinc',      10000],
                                    ['cu', 'Copper',    10000],
                                    ['b',  'Boron',     10000],
                                ];
                                foreach ($elements2 as [$id, $label, $factor]): ?>
                                <div class="col-md-2">
                                    <small class="form-text text-muted"><?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?></small>
                                    <div class="input-group input-group-sm mb-3">
                                        <input type="text" class="form-control form-control-sm"
                                               name="<?= $id ?>" id="<?= $id ?>"
                                               placeholder="<?= htmlspecialchars($id . ' - ' . $label, ENT_QUOTES, 'UTF-8') ?>">
                                        <input class="btn btn-append" type="button"
                                               id="btn_<?= $id ?>" value="ppm"
                                               onclick="conversion(this, document.getElementById('<?= $id ?>'), <?= $factor ?>)">
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>

                            <div class="row">
                                <?php
                                $elements3 = [
                                    ['m',  'Molybdenum', 10000],
                                    ['co', 'Cobalt',     10000],
                                    ['se', 'Selenium',   10000],
                                    ['ch', 'Chloride',   10000],
                                ];
                                foreach ($elements3 as [$id, $label, $factor]): ?>
                                <div class="col-md-2">
                                    <small class="form-text text-muted"><?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?></small>
                                    <div class="input-group input-group-sm mb-3">
                                        <input type="text" class="form-control form-control-sm"
                                               name="<?= $id ?>" id="<?= $id ?>"
                                               placeholder="<?= htmlspecialchars($id . ' - ' . $label, ENT_QUOTES, 'UTF-8') ?>">
                                        <input class="btn btn-append" type="button"
                                               id="btn_<?= $id ?>" value="ppm"
                                               onclick="conversion(this, document.getElementById('<?= $id ?>'), <?= $factor ?>)">
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>

                            <button type="submit" class="btn btn-success">Submit</button>
                        </form>

                        <?php include __DIR__ . '/../../../components/newClientModal.php'; ?>

                        <hr>

                        <div class="card mt-3">
                            <div class="card-body">
                                <h5 class="card-title">Excel/CSV Upload</h5>
                                <p class="card-text">Download a CSV of this form for easy filling or upload a filled form to pre-populate.</p>
                                <div class="input-group mt-3">
                                    <input type="file" class="form-control" id="upload" accept=".csv">
                                    <button class="btn btn-success" type="button" id="download">Download</button>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </main>

        <?php include __DIR__ . '/../../../layouts/footer.php'; ?>
    </div>
</div>

<script>
function conversion(btnEl, element, factor) {
    var val = parseFloat(element.value) || 0;
    if (btnEl.value === 'ppm') {
        btnEl.value = '%';
        element.value = (val / factor).toFixed(4);
    } else {
        btnEl.value = 'ppm';
        element.value = (val * factor).toFixed(2);
    }
}

// CSV download
document.getElementById('download').addEventListener('click', function () {
    var data = [['id', 'value']];
    document.querySelectorAll('#WatercsvForm input:not([type=hidden]):not([type=button]):not([type=submit]), #WatercsvForm select').forEach(function (el) {
        if (el.id) data.push([el.id, el.value]);
    });
    var csv = data.map(function (r) { return r.join(','); }).join('\n');
    var today = new Date();
    var fname = today.getDate() + '' + (today.getMonth() + 1) + '' + today.getFullYear() + '-water.csv';
    var link = document.createElement('a');
    link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv));
    link.setAttribute('download', fname);
    link.click();
});

// CSV upload
document.getElementById('upload').addEventListener('change', function (e) {
    var file = e.target.files[0];
    if (!file) return;
    var reader = new FileReader();
    reader.onload = function (ev) {
        ev.target.result.split('\n').slice(1).forEach(function (line) {
            var parts = line.split(',');
            var el = document.getElementById(parts[0]);
            if (el) el.value = parts[1] || '';
        });
    };
    reader.readAsText(file);
});

// Bootstrap validation
(function () {
    'use strict';
    document.querySelectorAll('.needs-validation').forEach(function (form) {
        form.addEventListener('submit', function (event) {
            if (!form.checkValidity()) {
                event.preventDefault();
                event.stopPropagation();
            }
            form.classList.add('was-validated');
        }, false);
    });
})();
</script>
