<?php
/**
 * soil-report-pdf.php
 *
 * Printable / PDF-export version of a soil analysis report.
 * NOTE: The [[!soilAnalysisReportCalcs?]] and [[!soilProgramCalcs?]] snippet
 * sections are pending full PHP migration. They currently render as blank.
 */

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();

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

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

$row  = null;
$today = date('jS F Y');

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');
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Soil Analysis Report | Crop Monitor</title>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>
    <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; }
        }
        .title th, .title td { padding: 2px 6px; }
    </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 class="col-md-9"></div>
    </div>

    <table class="title w-100 mb-3">
        <tbody>
            <tr>
                <td class="text-end fw-bold">DATE:</td>
                <td><?= $h($today) ?></td>
                <td></td>
                <td class="text-end fw-bold">SAMPLE ID:</td>
                <td><?= $h($row['site_id']) ?></td>
            </tr>
            <tr>
                <td class="text-end fw-bold">CLIENT:</td>
                <td><?= $h($row['client_name']) ?></td>
                <td></td>
                <td class="text-end fw-bold">DATE SAMPLED:</td>
                <td><?= $h($row['date_sampled']) ?></td>
            </tr>
            <tr>
                <td class="text-end fw-bold">ADDRESS:</td>
                <td><?= $h($row['site_address']) ?></td>
                <td></td>
                <td class="text-end fw-bold">LAB NUMBER:</td>
                <td><?= $h($row['lab_no']) ?></td>
            </tr>
            <tr>
                <td></td>
                <td><?= $h($row['state_postcode']) ?></td>
                <td></td>
                <td class="text-end fw-bold">CROP:</td>
                <td><?= $h($row['sample_id']) ?></td>
            </tr>
            <tr>
                <td></td>
                <td><?= $h($row['email']) ?></td>
                <td colspan="3"></td>
            </tr>
        </tbody>
    </table>

    <!-- Download button (hidden on print) -->
    <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">Soil Analysis Summary</div>
    </div>

    <!-- Analysis calculation sections — pending PHP migration of soilAnalysisReportCalcs -->
    <div class="row bg-dark text-white p-2 mt-3">
        <div class="text-center col-md-12 h5">
            Total kilograms per hectare of each element needed to balance soil in this test
        </div>
    </div>
    <div class="row">
        <div class="col text-muted fst-italic p-3">
            [Soil analysis calculation components pending migration]
        </div>
    </div>

    <hr>

    <!-- Report form (auto-saves via AJAX) -->
    <form class="report-form" method="post">
        <input type="hidden" name="csrf_token" value="<?= $h(generateCsrfToken()) ?>">

        <div class="row bg-dark text-white p-2 mt-3">
            <div class="text-center col-md-12 h5">Overview</div>
        </div>
        <div class="row">
            <div class="col-md-12 p-0">
                <textarea class="form-control rounded-0" rows="5" id="overview" name="overview"></textarea>
            </div>
        </div>

        <hr>

        <div class="row bg-dark text-white p-2 mt-3">
            <div class="text-center col-md-12 h5">
                Ideal Soil Balancing Program for One Season of a FIVE YEAR Plan
            </div>
        </div>
        <div class="col text-muted fst-italic p-3">
            [Soil program calculation components pending migration]
        </div>

        <hr>

        <div class="row bg-dark text-white p-2 mt-3">
            <div class="text-center col-md-12 h5">
                <input type="text" class="text-center form-control-plaintext text-white border-dark bg-dark"
                       name="header1" id="header1" value="Foliar Program">
            </div>
        </div>
        <div class="row">
            <div class="col-md-12 p-0">
                <textarea class="form-control rounded-0" rows="5"
                          id="foliar_Details" name="foliar_Details"></textarea>
            </div>
        </div>

        <div class="row bg-dark text-white p-2 mt-3">
            <div class="text-center col-md-12 h5">Microbe Program</div>
        </div>
        <div class="row">
            <div class="col-md-12 p-0">
                <textarea class="form-control rounded-0" rows="5"
                          id="microbe_Program" name="microbe_Program"></textarea>
            </div>
        </div>

        <div class="row mt-2">
            <p class="small fst-italic text-muted">
                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>

    </form>

    <?php endif; ?>

</div><!-- /container -->

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
<script>
$(document).ready(function () {
    var timeoutId;
    var saveUrl = '/dashboard/crop-analysis/updatecomment.php'
                + '?rid=<?= (int) $recordId ?>&rand=<?= (float) $randId ?>';

    $('form textarea, form input[name="header1"]').on('input propertychange change', function () {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(saveToDB, 1000);
    });

    function saveToDB() {
        var form = $('.report-form');
        $.ajax({
            url: saveUrl,
            type: 'POST',
            data: form.serialize(),
            beforeSend: function () { $('.form-status-holder').html('Saving...'); },
            success: function (data) {
                var d = new Date();
                $('.form-status-holder').html('Saved! Last: ' + d.toLocaleTimeString());
            }
        });
    }

    $('.report-form').submit(function (e) {
        saveToDB();
        e.preventDefault();
    });

    // PDF download
    $('.downloadPDF').click(function () {
        var element = document.getElementById('content');
        var opt = {
            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' }
        };
        html2pdf().from(element).set(opt).save();
    });
});
</script>

</body>
</html>
