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

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

requireLogin();

$client_id = (int)  ($_GET['cid']  ?? 0);
$record_id = (int)  ($_GET['rid']  ?? 0);
$rand_id   = (float)($_GET['rand'] ?? 0);
$croptype  = htmlspecialchars(trim($_GET['stid'] ?? ''), ENT_QUOTES, 'UTF-8');

if (!$record_id || !$rand_id) {
    http_response_code(400);
    die('Invalid request parameters.');
}

try {
    $pdo  = getDBConnection();
    $stmt = $pdo->prepare(
        'SELECT * FROM `soil_records` WHERE `id` = ? AND `rand` = ? LIMIT 1'
    );
    $stmt->execute([$record_id, $rand_id]);
    $row = $stmt->fetch();
} catch (PDOException $e) {
    error_log('soil-analysis-pdf.php DB error: ' . $e->getMessage());
    http_response_code(500);
    die('Database error.');
}

if (!$row) {
    http_response_code(404);
    die('Record not found.');
}

// All values escaped for HTML output
$h = fn($v) => htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');

$client     = $h($row['client_name']);
$address    = $h($row['site_address']);
$state      = $h($row['state_postcode']);
$email      = $h($row['email']);
$labNo      = $h($row['lab_no']);
$sampleDate = $h($row['date_sampled']);
$sample     = $h($row['site_id']);
$crop       = $h($row['sample_id']);
$today      = date('jS F Y');

// Navigation URLs (replacing modX [[~41~]], [[~66~]], [[~37~]] resource links)
$params      = http_build_query(['rand' => $rand_id, 'cid' => $client_id, 'rid' => $record_id, 'stid' => $croptype]);
$analysisUrl = '/dashboard/crop-analysis/soil-test-data/soil-analysis.php?' . $params;
$reportUrl   = '/dashboard/crop-analysis/soil-test-data/soil-report.php?' . $params;
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Soil Analysis PDF | 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" 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"
            integrity="sha512-YcsIPGdhPK4P/uRW6/sruonlYj+Q7UHWeKfTAkBW+g83NKM+jMJFJ4iAPfSnVp7BKD4dKMHmVSvICUbE/V1sSw=="
            crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <style>
        @media print {
            @page { size: A4 portrait; margin: 1cm; }
        }
    </style>
</head>
<body>

<div class="grid">

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

    <table class="title">
        <tbody>
            <tr>
                <td class="right"><b>DATE:</b></td>
                <td class="left"><?= $today ?></td>
                <td></td>
                <td class="right"><b>SAMPLE ID:</b></td>
                <td class="left"><?= $sample ?></td>
            </tr>
            <tr>
                <td class="right"><b>CLIENT:</b></td>
                <td class="left"><?= $client ?></td>
                <td></td>
                <td class="right"><b>DATE SAMPLED:</b></td>
                <td class="left"><?= $sampleDate ?></td>
            </tr>
            <tr>
                <td class="right"><b>ADDRESS:</b></td>
                <td class="left"><?= $address ?></td>
                <td></td>
                <td class="right"><b>LAB NUMBER:</b></td>
                <td class="left"><?= $labNo ?></td>
            </tr>
            <tr>
                <td class="right"></td>
                <td class="left"><?= $state ?></td>
                <td></td>
                <td class="right"><b>CROP:</b></td>
                <td class="left"><?= $crop ?></td>
            </tr>
            <tr>
                <td class="right"></td>
                <td class="left"><?= $email ?></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
        </tbody>
    </table>

    <div class="clearfix"></div>

    <!-- Navigation buttons (hidden on print) -->
    <div class="pdfHide">
        <a href="<?= $analysisUrl ?>" target="_blank">
            <input type="button" class="button" value="Analysis Page">
        </a>
        <a href="<?= $reportUrl ?>" target="_blank">
            <input type="button" class="button" value="Soil Report">
        </a>
        <button class="btn btn-sm btn-secondary downloadPDF">Download PDF</button>
    </div>

    <div class="nav-wrap">
        <div class="graph-header text-center">ANALYSIS RESULTS</div>
    </div>
    <div class="clearfix"></div>
    <hr>

    <!-- Analysis table rows are still rendered by [[!soilAnalysisCalcs]] snippets
         which need to be migrated to PHP calls — tracked in CLAUDE.md.
         The SQL injection and auth vulnerabilities in this file are now resolved. -->

</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
<script>
    document.querySelectorAll('.downloadPDF').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var element = document.body;
            html2pdf().from(element).set({
                margin:      3,
                filename:    'soil-analysis.pdf',
                image:       { type: 'jpeg', quality: 1.0 },
                html2canvas: { scale: 2, letterRendering: true, windowWidth: 1024 },
                jsPDF:       { orientation: 'portrait', unit: 'mm', format: 'a4' }
            }).save();
        });
    });
</script>
</body>
</html>
