<?php
/**
 * plant-report.php
 *
 * Displays the plant analysis consultant notes / PDF report.
 * Accessed via rid + rand URL params.
 * Notes auto-save to the reports table via plant-report-save.php.
 */

require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../lib/auth.php';

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

requireLogin();

$pdo    = getDBConnection();
$userId = getCurrentUserId();

$recordId = (int)   ($_GET['rid']  ?? 0);
$randId   = (float) ($_GET['rand'] ?? 0);

$row   = null;
$notes = ['general_details' => '', 'recommended_details' => '', 'foliar_details' => ''];

if ($recordId > 0) {
    $stmt = $pdo->prepare('SELECT * FROM plant_records WHERE id = ? AND rand = ? LIMIT 1');
    $stmt->execute([$recordId, $randId]);
    $row = $stmt->fetch();
}

if ($row) {
    $rpt = $pdo->prepare(
        'SELECT comment FROM reports WHERE record_id = ? AND modx_user_id = ? ORDER BY id DESC LIMIT 1'
    );
    $rpt->execute([$recordId, $userId]);
    $saved = $rpt->fetchColumn();
    if ($saved) {
        $decoded = json_decode($saved, true);
        if (is_array($decoded)) {
            $notes = array_merge($notes, $decoded);
        }
    }
}

$h = fn($v) => htmlspecialchars((string) $v, ENT_QUOTES, 'UTF-8');
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Plant Analysis Report | Crop Monitor</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.css" crossorigin="anonymous" rel="stylesheet">
    <link href="/client-assets/css/dashboard-2021.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.3/html2pdf.bundle.min.js" crossorigin="anonymous"></script>
    <style>
        @media print {
            @page { size: A4 portrait; margin: 0.5cm; }
            .d-print-none { display: none !important; }
        }
        .chart-header     { background: #343a40; color: white; text-align: center; padding: 6px; }
        .chart-header-sub { background: #6c757d; color: white; text-align: center; padding: 4px; }
        textarea { width: 100%; min-height: 120px; border: 1px solid #dee2e6; padding: 8px; font-size: 0.9rem; }
        .save-status { font-size: 0.75rem; color: #6c757d; }
    </style>
</head>
<body>
<div class="container" id="content">

    <?php if (!$row): ?>
        <div class="alert alert-danger mt-4">Record not found or access denied.</div>
    <?php else: ?>

    <div class="row mb-3">
        <div class="col-md-3">
            <img class="img-fluid" src="/client-assets/images/crop-monitor.png" alt="Crop Monitor">
        </div>
    </div>

    <div class="d-print-none mb-3 d-flex align-items-center gap-2">
        <button class="btn btn-success btn-sm downloadPDF">
            <i class="fas fa-download me-1"></i>Download PDF
        </button>
        <span class="save-status" id="saveStatus"></span>
    </div>

    <!-- Client info -->
    <table class="table table-sm table-bordered mb-3" style="font-size:0.85rem;">
        <tbody>
            <tr>
                <th class="w-25">Client</th>
                <td><?= $h($row['client_name'] ?? '') ?></td>
                <th class="w-25">Lab No</th>
                <td><?= $h($row['lab_no'] ?? '') ?></td>
            </tr>
            <tr>
                <th>Sample ID</th>
                <td><?= $h($row['sample_id'] ?? '') ?></td>
                <th>Site ID</th>
                <td><?= $h($row['site_id'] ?? '') ?></td>
            </tr>
            <tr>
                <th>Crop</th>
                <td><?= $h($row['crop_type'] ?? '') ?></td>
                <th>Date Sampled</th>
                <td><?= $h($row['date_sampled'] ?? '') ?></td>
            </tr>
        </tbody>
    </table>

    <div class="text-center fw-bold h5 mb-3">PLANT ANALYSIS SUMMARY</div>

    <form class="report-form">
        <!-- General Comment -->
        <div class="chart-header mb-1">General Comment</div>
        <div class="mb-3">
            <textarea id="general_details" name="general_details"><?= $h($notes['general_details']) ?></textarea>
        </div>

        <!-- Recommended Program -->
        <div class="chart-header mb-1">Recommended Remedial Program</div>
        <div class="mb-3">
            <textarea id="recommended_details" name="recommended_details"><?= $h($notes['recommended_details']) ?></textarea>
        </div>

        <!-- Foliar Program -->
        <div class="chart-header mb-1">Foliar Program</div>
        <div class="mb-3">
            <textarea id="foliar_details" name="foliar_details"><?= $h($notes['foliar_details']) ?></textarea>
        </div>
    </form>

    <div class="mt-4 small text-muted">
        <p><i class="fa fa-leaf" style="color:green"></i> It is always an advantage to assess tissue analysis results along with a corresponding soil analysis for more accurate diagnosis of plant nutrient status.</p>
        <p><i class="fa fa-leaf" style="color:green"></i> Trace element levels — manganese, copper and zinc — can all be affected by fungicide spray residues, giving misleading results.</p>
        <p><i class="fa fa-leaf" style="color:green"></i> Talk to your qualified consultant to make a plan for correction or maintenance of the found nutrient levels.</p>
        <p style="font-style:italic;font-size:9px;">Desired ranges indexed from: CSIRO Plant Analysis Handbook 2nd Ed. Hill Laboratories consultants guide. PIRSA Soil and Plant Analysis.</p>
        <p style="font-style:italic;font-size:9px;">Any recommendations provided by Cropmonitor are advice only. We are not paid consultants and are not covered to accept responsibility for any of our suggestions.</p>
    </div>

    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
<script>
(function () {
    var timeoutId;
    var form = document.querySelector('.report-form');
    if (!form) return;

    form.querySelectorAll('textarea').forEach(function (el) {
        el.addEventListener('input', function () {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(saveToDB, 1200);
        });
    });

    function saveToDB() {
        var data = new FormData(form);
        var params = new URLSearchParams();
        data.forEach(function (v, k) { params.append(k, v); });

        document.getElementById('saveStatus').textContent = 'Saving…';

        fetch('/dashboard/crop-analysis/plant-test-data/plant-report-save.php?rid=<?= (int)$recordId ?>&rand=<?= (float)$randId ?>', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: params.toString()
        })
        .then(function (r) { return r.json(); })
        .then(function (d) {
            document.getElementById('saveStatus').textContent = d.success ? ('Saved ' + d.saved) : 'Save failed';
        })
        .catch(function () {
            document.getElementById('saveStatus').textContent = 'Save error';
        });
    }
})();

document.querySelector('.downloadPDF') && document.querySelector('.downloadPDF').addEventListener('click', function () {
    var opt = {
        margin: 3,
        filename: 'plant-report.pdf',
        image: { type: 'jpeg', quality: 1.0 },
        html2canvas: { scale: 2, letterRendering: true, windowWidth: 1024 },
        jsPDF: { orientation: 'portrait', unit: 'mm', format: 'a4' }
    };
    html2pdf().from(document.getElementById('content')).set(opt).save();
});
</script>
</body>
</html>
