<?php
/**
 * soil-analysis-bs.php
 *
 * Displays soil analysis ratios and key calculated values for a soil record.
 * 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;
if ($recordId > 0) {
    $stmt = $pdo->prepare('SELECT * FROM soil_records WHERE id = ? AND rand = ? LIMIT 1');
    $stmt->execute([$recordId, $randId]);
    $row = $stmt->fetch();
}

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

/**
 * Render a ratio row: element1 / element2, with a simple status bar.
 * Returns 3 <td> cells: Deficit | Ideal | High
 */
function ratioBar(float $a, float $b, float $idealMin, float $idealMax): string {
    if ($b <= 0) return '<td colspan="3" class="text-muted text-center small">N/A</td>';
    $ratio = $a / $b;
    if ($idealMax <= 0) return '<td colspan="3" class="text-center small">' . number_format($ratio, 2) . ':1</td>';

    if ($ratio < $idealMin) {
        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 ($ratio > $idealMax) {
        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 {
        $range = $idealMax - $idealMin;
        $pct   = $range > 0 ? min(100, max(0, ($ratio - $idealMin) / $range * 100)) : 50;
        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>Soil Analysis Ratios | 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; }
        .lightblue { background: #cce5ff !important; color: #004085 !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>

    <div class="row">
        <div class="col-md-12 text-center fw-bold h4">ANALYSIS RESULTS — RATIOS</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">Ratio</th>
                <th class="text-center border-bottom">Ideal Range</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">RATIOS</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
            // Ca:Mg  ideal 2:1 – 5:1
            $ca = (float)($row['ca_mehlick3'] ?? 0);
            $mg = (float)($row['mg_mehlick3'] ?? 0);
            $k  = (float)($row['k_mehlick3']  ?? 0);
            $na = (float)($row['na_mehlick3'] ?? 0);
            $p  = (float)($row['p_mehlick']   ?? 0);
            $s  = (float)($row['s_morgan']    ?? 0);
            $zn = (float)($row['zn_dtpa']     ?? 0);
            $fe = (float)($row['fe_dtpa']     ?? 0);
            $mn = (float)($row['mn_dtpa']     ?? 0);
            $c  = (float)($row['ocarbon']     ?? 0);
            $n  = (float)($row['NO3_N']       ?? 0);

            $ratios = [
                ['Ca:Mg Ratio',  $ca, $mg,  2.0,  5.0,  'Ca / Mg'],
                ['Mg:K Ratio',   $mg, $k,   2.0,  6.0,  'Mg / K'],
                ['K:Na Ratio',   $k,  $na,  5.0, 20.0,  'K / Na'],
                ['P:S Ratio',    $p,  $s,   1.0,  4.0,  'P / S'],
                ['P:Zn Ratio',   $p,  $zn,  8.0, 16.0,  'P / Zn'],
                ['Fe:Mn Ratio',  $fe, $mn,  1.5,  3.5,  'Fe / Mn'],
                ['C:N Ratio',    $c,  $n,   8.0, 15.0,  'C / N'],
            ];

            foreach ($ratios as [$label, $numerator, $denominator, $idealMin, $idealMax, $formula]):
                $ratio    = ($denominator > 0) ? $numerator / $denominator : 0;
                $idealStr = number_format($idealMin, 1) . ':1 – ' . number_format($idealMax, 1) . ':1';
                $foundStr = ($denominator > 0) ? number_format($ratio, 2) . ':1' : '—';
            ?>
            <tr>
                <td class="border-left"><?= $h($label) ?></td>
                <td><?= $h($idealStr) ?></td>
                <td><?= $h($foundStr) ?></td>
                <?= ratioBar($numerator, $denominator, $idealMin, $idealMax) ?>
            </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 lightblue">KEY VALUES</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
            $keyValues = [
                ['Total Nitrogen (NH3-N)', (float)($row['NH3_N']   ?? 0), '%', 0.15, 0.40],
                ['Total Carbon (OC)',      (float)($row['ocarbon']  ?? 0), '%', 1.5,  4.0],
            ];
            foreach ($keyValues as [$label, $found, $unit, $min, $max]):
                $pct     = ($max > $min && $found > 0) ? min(100, max(0, ($found - $min) / ($max - $min) * 100)) : 0;
                $desired = number_format($min, 2) . '–' . number_format($max, 2);
                if ($found < $min) {
                    $bar = '<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) {
                    $bar = '<td></td><td></td><td class="text-center"><div class="progress"><div class="progress-bar bg-warning" style="width:100%"></div></div></td>';
                } else {
                    $bar = '<td></td><td class="text-center"><div class="progress"><div class="progress-bar bg-success" style="width:' . round($pct) . '%"></div></div></td><td></td>';
                }
            ?>
            <tr>
                <td class="border-left"><?= $h($label) ?> (<?= $h($unit) ?>)</td>
                <td><?= $h($desired) ?></td>
                <td><?= $found > 0 ? number_format($found, 3) : '—' ?></td>
                <?= $bar ?>
            </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-leaf" style="color:green"></i> Ideal ratio ranges are indicative. Consult your agronomist for crop and region-specific guidance.</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: 'soil-analysis-ratios.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>
