<?php
/**
 * water-analysis-pdf.php
 *
 * Displays water quality analysis results for a single water_records row.
 * Standalone PDF-printable page. Accessed via rid + rand URL params.
 */

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;
$specs = [];

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

if ($row) {
    $type = $row['analysis_type'] ?? '';
    $stmt = $pdo->prepare('SELECT * FROM water_specifications WHERE type = ? LIMIT 1');
    $stmt->execute([$type]);
    $specs = $stmt->fetch() ?: [];
}

$h = fn($v) => htmlspecialchars((string) $v, ENT_QUOTES, 'UTF-8');

function waterBar(float $found, float $min, float $max): string {
    if ($max <= 0) return '<td colspan="3" class="text-muted text-center small">N/A</td>';
    $pct = ($max > $min) ? min(100, max(0, ($found - $min) / ($max - $min) * 100)) : 0;
    if ($found < $min) {
        return '<td class="text-center"><div class="progress"><div class="progress-bar bg-danger" style="width:100%"></div></div></td>'
             . '<td></td><td></td>';
    } elseif ($found > $max) {
        return '<td></td><td></td>'
             . '<td class="text-center"><div class="progress"><div class="progress-bar bg-warning" style="width:100%"></div></div></td>';
    } else {
        return '<td></td>'
             . '<td class="text-center"><div class="progress"><div class="progress-bar bg-success" style="width:' . round($pct) . '%"></div></div></td>'
             . '<td></td>';
    }
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Water Analysis | 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; }
        }
        .progress { border-radius: 0 !important; }
        table.chart { width: 100%; border-collapse: collapse; }
        table.chart th, table.chart td { padding: 3px 6px; font-size: 0.85rem; }
        .chart-header th { background: #343a40; color: white; }
        .chart-header-sub th { background: #6c757d; color: white; }
        .lightgreen  { background: #d4edda !important; color: #155724 !important; }
        .lightred    { background: #f8d7da !important; color: #721c24 !important; }
        .lightblue   { background: #cce5ff !important; color: #004085 !important; }
        .lightpurple { background: #e2d9f3 !important; color: #432874 !important; }
        .stripe-1    { background: #f8f9fa; }
        .border-left   { border-left:   1px solid #dee2e6; }
        .border-right  { border-right:  1px solid #dee2e6; }
        .border-bottom { border-bottom: 1px solid #dee2e6; }
        .border-top    { border-top:    1px solid #dee2e6; }
    </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">
        <button class="btn btn-success btn-sm downloadPDF">
            <i class="fas fa-download me-1"></i>Download PDF
        </button>
    </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>Analysis Type</th>
                <td><?= $h($row['analysis_type'] ?? '') ?></td>
                <th>Date Sampled</th>
                <td><?= $h($row['date_sampled'] ?? '') ?></td>
            </tr>
        </tbody>
    </table>

    <div class="row">
        <div class="col-md-12 text-center fw-bold h4">ANALYSIS RESULTS</div>
    </div>
    <hr class="p-1 m-1">

    <table class="chart">
        <tbody>
            <tr class="chart-header">
                <th colspan="3" class="text-center border-left border-right border-top">ELEMENT</th>
                <th colspan="3" class="text-center border-right border-top">STATUS</th>
            </tr>
            <tr class="chart-header-sub">
                <th class="text-center border-bottom border-left">Parameter</th>
                <th class="text-center border-bottom">Desired</th>
                <th class="text-center border-bottom">Found</th>
                <th class="text-center stripe-1">Deficit</th>
                <th class="text-center stripe-1">Ideal</th>
                <th class="text-center border-right stripe-1">High</th>
            </tr>

            <tr><td class="border-left" colspan="6"></td></tr>
            <tr class="chart-header-sub">
                <th colspan="3" class="border-left text-center lightblue">GENERAL PARAMETERS</th>
                <th class="text-center border-left stripe-1"></th>
                <th class="text-center border-left stripe-1"></th>
                <th class="text-center border-left border-right stripe-1"></th>
            </tr>

            <?php
            $generalParams = [
                ['ph',       'pH',                          ''],
                ['cond_dsm', 'Conductivity',                'dS/m'],
                ['hco3-',    'Bicarbonate (HCO₃)',          'ppm'],
            ];
            foreach ($generalParams as [$col, $label, $unit]):
                $found = (float)($row[$col] ?? 0);
                $min   = (float)($specs[$col . '_min'] ?? 0);
                $max   = (float)($specs[$col . '_max'] ?? 0);
                $desired = ($min > 0 || $max > 0) ? number_format($min, 2) . '–' . number_format($max, 2) : '—';
                $display = $unit ? $label . ' (' . $unit . ')' : $label;
            ?>
            <tr>
                <td class="border-left"><?= $h($display) ?></td>
                <td><?= $h($desired) ?></td>
                <td><?= $found > 0 ? number_format($found, 3) : '—' ?></td>
                <?= waterBar($found, $min, $max) ?>
            </tr>
            <?php endforeach; ?>

            <tr><td class="border-left" colspan="6"></td></tr>
            <tr class="chart-header-sub">
                <th colspan="3" class="border-left text-center lightgreen">MAJOR ELEMENTS</th>
                <th class="text-center border-left stripe-1"></th>
                <th class="text-center border-left stripe-1"></th>
                <th class="text-center border-left border-right stripe-1"></th>
            </tr>

            <?php
            $majorElements = [
                ['nh4', 'Ammonium Nitrogen (NH₄)', 'ppm'],
                ['no3', 'Nitrate Nitrogen (NO₃)',  'ppm'],
                ['p',   'Phosphorus',               'ppm'],
                ['k',   'Potassium',                'ppm'],
                ['s',   'Sulphur',                  'ppm'],
                ['ca',  'Calcium',                  'ppm'],
                ['mg',  'Magnesium',                'ppm'],
                ['na',  'Sodium',                   'ppm'],
            ];
            foreach ($majorElements as [$col, $label, $unit]):
                $found = (float)($row[$col] ?? 0);
                $min   = (float)($specs[$col . '_min'] ?? 0);
                $max   = (float)($specs[$col . '_max'] ?? 0);
                $desired = ($min > 0 || $max > 0) ? number_format($min, 1) . '–' . number_format($max, 1) : '—';
            ?>
            <tr>
                <td class="border-left"><?= $h($label) ?> (<?= $h($unit) ?>)</td>
                <td><?= $h($desired) ?></td>
                <td><?= $found > 0 ? number_format($found, 2) : '—' ?></td>
                <?= waterBar($found, $min, $max) ?>
            </tr>
            <?php endforeach; ?>

            <tr><td class="border-left" colspan="6"></td></tr>
            <tr class="chart-header-sub">
                <th colspan="3" class="border-left text-center lightred">TRACE ELEMENTS</th>
                <th class="text-center border-left stripe-1"></th>
                <th class="text-center border-left stripe-1"></th>
                <th class="text-center border-left border-right stripe-1"></th>
            </tr>

            <?php
            $traceElements = [
                ['fe', 'Iron',      'ppm'],
                ['mn', 'Manganese', 'ppm'],
                ['zn', 'Zinc',      'ppm'],
                ['cu', 'Copper',    'ppm'],
                ['b',  'Boron',     'ppm'],
                ['m',  'Molybdenum','ppm'],
                ['co', 'Cobalt',    'ppm'],
            ];
            foreach ($traceElements as [$col, $label, $unit]):
                $found = (float)($row[$col] ?? 0);
                $min   = (float)($specs[$col . '_min'] ?? 0);
                $max   = (float)($specs[$col . '_max'] ?? 0);
                $desired = ($min > 0 || $max > 0) ? number_format($min, 2) . '–' . number_format($max, 2) : '—';
            ?>
            <tr>
                <td class="border-left"><?= $h($label) ?> (<?= $h($unit) ?>)</td>
                <td><?= $h($desired) ?></td>
                <td><?= $found > 0 ? number_format($found, 3) : '—' ?></td>
                <?= waterBar($found, $min, $max) ?>
            </tr>
            <?php endforeach; ?>

            <tr>
                <td class="border-bottom border-left"></td>
                <td class="border-bottom"></td>
                <td class="border-bottom"></td>
                <td class="border-bottom"></td>
                <td class="border-bottom"></td>
                <td class="border-bottom border-right"></td>
            </tr>
        </tbody>
    </table>

    <div class="mt-4 small text-muted">
        <p><i class="fa fa-tint" style="color:#007bff"></i> Water analysis results should be interpreted in the context of intended use (irrigation, drinking, stock water).</p>
        <p><i class="fa fa-tint" style="color:#007bff"></i> Talk to your qualified consultant to make a plan for correction or maintenance of the found parameter levels.</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>
document.querySelector('.downloadPDF') && document.querySelector('.downloadPDF').addEventListener('click', function () {
    var opt = {
        margin: 3,
        filename: 'water-analysis.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>
