<?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 = 'Plant Tissue Analysis';
$siteName  = 'Crop Monitor';

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

<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">Plant Test Data</li>
                </ol>

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

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

                        <form method="post" action="/controllers/plantTestSubmit.php" id="PlantcsvForm" 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">
                                </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 class="col">
                                    <small class="form-text text-muted">Crop Type</small>
                                    <input type="text" class="form-control form-control-sm" name="crop_type" id="crop_type" placeholder="Crop Type">
                                </div>
                            </div>

                            <hr>
                            <label><b>Major Elements (% dry weight)</b></label>
                            <div class="row mt-2">
                                <div class="col-md-2">
                                    <small class="form-text text-muted">Nitrogen (N) %</small>
                                    <input type="text" class="form-control form-control-sm" name="n" id="n" placeholder="0.00">
                                </div>
                                <div class="col-md-2">
                                    <small class="form-text text-muted">Phosphorus (P) %</small>
                                    <input type="text" class="form-control form-control-sm" name="p" id="p" placeholder="0.00">
                                </div>
                                <div class="col-md-2">
                                    <small class="form-text text-muted">Potassium (K) %</small>
                                    <input type="text" class="form-control form-control-sm" name="k" id="k" placeholder="0.00">
                                </div>
                                <div class="col-md-2">
                                    <small class="form-text text-muted">Sulphur (S) %</small>
                                    <input type="text" class="form-control form-control-sm" name="s" id="s" placeholder="0.00">
                                </div>
                                <div class="col-md-2">
                                    <small class="form-text text-muted">Magnesium (Mg) %</small>
                                    <input type="text" class="form-control form-control-sm" name="mg" id="mg" placeholder="0.00">
                                </div>
                                <div class="col-md-2">
                                    <small class="form-text text-muted">Calcium (Ca) %</small>
                                    <input type="text" class="form-control form-control-sm" name="ca" id="ca" placeholder="0.00">
                                </div>
                            </div>
                            <div class="row mt-2">
                                <div class="col-md-2">
                                    <small class="form-text text-muted">Sodium (Na) %</small>
                                    <input type="text" class="form-control form-control-sm" name="na" id="na" placeholder="0.00">
                                </div>
                            </div>

                            <hr>
                            <label><b>Trace Elements (ppm)</b></label>
                            <div class="row mt-2">
                                <div class="col-md-2">
                                    <small class="form-text text-muted">Iron (Fe) ppm</small>
                                    <input type="text" class="form-control form-control-sm" name="fe" id="fe" placeholder="0.0">
                                </div>
                                <div class="col-md-2">
                                    <small class="form-text text-muted">Manganese (Mn) ppm</small>
                                    <input type="text" class="form-control form-control-sm" name="mn" id="mn" placeholder="0.0">
                                </div>
                                <div class="col-md-2">
                                    <small class="form-text text-muted">Zinc (Zn) ppm</small>
                                    <input type="text" class="form-control form-control-sm" name="zn" id="zn" placeholder="0.0">
                                </div>
                                <div class="col-md-2">
                                    <small class="form-text text-muted">Copper (Cu) ppm</small>
                                    <input type="text" class="form-control form-control-sm" name="cu" id="cu" placeholder="0.0">
                                </div>
                                <div class="col-md-2">
                                    <small class="form-text text-muted">Boron (B) ppm</small>
                                    <input type="text" class="form-control form-control-sm" name="b" id="b" placeholder="0.0">
                                </div>
                            </div>

                            <hr>
                            <label><b>Other Elements (ppm)</b></label>
                            <div class="row mt-2">
                                <div class="col-md-2">
                                    <small class="form-text text-muted">Molybdenum (Mo) ppm</small>
                                    <input type="text" class="form-control form-control-sm" name="m" id="m" placeholder="0.00">
                                </div>
                                <div class="col-md-2">
                                    <small class="form-text text-muted">Cobalt (Co) ppm</small>
                                    <input type="text" class="form-control form-control-sm" name="co" id="co" placeholder="0.00">
                                </div>
                                <div class="col-md-2">
                                    <small class="form-text text-muted">Selenium (Se) ppm</small>
                                    <input type="text" class="form-control form-control-sm" name="se" id="se" placeholder="0.00">
                                </div>
                                <div class="col-md-2">
                                    <small class="form-text text-muted">Chloride (Cl) ppm</small>
                                    <input type="text" class="form-control form-control-sm" name="cl" id="cl" placeholder="0.00">
                                </div>
                            </div>

                            <hr>
                            <button form="PlantcsvForm" type="submit" name="PlantcsvForm" 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">CSV Upload / Download</h5>
                                <p class="card-text text-muted">Download a CSV template or upload a filled CSV to pre-populate the form.</p>
                                <div class="input-group mt-2">
                                    <input type="file" class="form-control form-control-sm" id="csvUpload" accept=".csv">
                                    <button class="btn btn-success btn-sm" type="button" id="csvDownload">Download Template</button>
                                </div>
                            </div>
                        </div>

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

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

<script>
(function () {
    'use strict';
    window.addEventListener('load', function () {
        var forms = document.getElementsByClassName('needs-validation');
        Array.prototype.forEach.call(forms, function (form) {
            form.addEventListener('submit', function (event) {
                if (!form.checkValidity()) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    }, false);
})();

document.getElementById('csvUpload').addEventListener('change', function (e) {
    var file = e.target.files[0];
    if (!file) return;
    var reader = new FileReader();
    reader.onload = function (ev) {
        var rows = ev.target.result.split('\n');
        rows.forEach(function (row, i) {
            if (i === 0) return;
            var cols = row.split(',');
            if (cols.length >= 2) {
                var el = document.getElementById(cols[0].trim());
                if (el) el.value = cols[1].trim();
            }
        });
    };
    reader.readAsText(file);
});

document.getElementById('csvDownload').addEventListener('click', function () {
    var fields = ['lab_no','batch_no','date_sampled','sample_id','site_id','crop_type',
                  'n','p','k','s','mg','ca','na','fe','mn','zn','cu','b','m','co','se','cl'];
    var rows = [['id','value']];
    fields.forEach(function (id) {
        var el = document.getElementById(id);
        rows.push([id, el ? el.value : '']);
    });
    var csv = rows.map(function (r) { return r.join(','); }).join('\n');
    var a = document.createElement('a');
    a.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
    a.download = 'plant-tissue-analysis.csv';
    a.click();
});
</script>
