<?php
/**
 * dashboard/crop-analysis/soil-analysis.php
 *
 * Soil Analysis Results Display Page
 * Shows detailed soil test results with calculations and recommendations
 */

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

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Require authentication
requireLogin();

// Get and validate parameters
$client_id = (int)($_GET['cid'] ?? 0);
$record_id = (float)($_GET['rid'] ?? 0);
$rand_id = (float)($_GET['rand'] ?? 0);

// Validate required parameters
if (!$record_id || !$rand_id) {
    die('Invalid request parameters');
}

// Get soil record data securely
try {
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("SELECT * FROM soil_records WHERE id = ? AND rand = ?");
    $stmt->execute([$record_id, $rand_id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        die('Soil record not found');
    }

    // Extract data
    $client = htmlspecialchars($row['client_name'] ?? '', ENT_QUOTES, 'UTF-8');
    $address = htmlspecialchars($row['site_address'] ?? '', ENT_QUOTES, 'UTF-8');
    $state = htmlspecialchars($row['state_postcode'] ?? '', ENT_QUOTES, 'UTF-8');
    $email = htmlspecialchars($row['email'] ?? '', ENT_QUOTES, 'UTF-8');
    $labNo = htmlspecialchars($row['lab_no'] ?? '', ENT_QUOTES, 'UTF-8');
    $sampleDate = htmlspecialchars($row['date_sampled'] ?? '', ENT_QUOTES, 'UTF-8');
    $sample = htmlspecialchars($row['site_id'] ?? '', ENT_QUOTES, 'UTF-8');
    $crop = htmlspecialchars($row['sample_id'] ?? '', ENT_QUOTES, 'UTF-8');

} catch (PDOException $e) {
    error_log("Database error in soil-analysis.php: " . $e->getMessage());
    die('Database error occurred');
}

$today = date('jS F Y');
$pageTitle = 'Soil Analysis Results - ' . $client;
$siteName = 'Crop Management Platform';
$activeItem = 'Soil Analysis';

include __DIR__.'/../../layouts/header.php';
include __DIR__.'/../../layouts/navbar.php';
?>

<div id="layoutSidenav">
    <div id="layoutSidenav_nav">
        <?php include __DIR__.'/../../layouts/sidebar.php'; ?>
    </div>
    <div id="layoutSidenav_content">
        <main>
            <div class="container-fluid px-4">            <div class="row">
                <?php
                // Replace Logo with Customer Logo if supplied.
                $client = '';

                echo "<div class='col-md-3'>";
                if ($client === "") {
                    echo "<img class='img-fluid' src='client-assets/images/crop-monitor.png'  alt='Crop Monitor' >";    
                } else {
                    echo "<img class='img-fluid' src='client-assets/images/crop-monitor.png'  alt='Crop Monitor' >";
                }

                //echo "<span class='col'></span>";


                //Client Test Description
                if ($client === "") {
                    echo "";    
                } else {
                    echo "<img class='img-fluid' src='client-assets/images/crop-monitor.png'  alt='Crop Monitor' >";
                }
                echo "</div>";

                echo "<div class='col-md-9'></div>";
                ?>
            </div>

            <table class='title'>
                <tbody>
                    <tr>
                        <th class='col-20'></th>
                        <th class='col-20'></th>
                        <th class='col-20'></th>
                        <th class='col-20'></th>
                        <th class='col-20'></th>
                    </tr>
                    <tr>
                        <td class='right'><b>DATE:</b></td>
                        <td class='left'><?php echo $today; ?></td>
                        <td></td>
                        <td class='right'><b>SAMPLE ID:</b></td>
                        <td class='left'><?php echo $sample; ?></td>
                    </tr>
                    <tr>
                        <td class='right'><b>CLIENT:</b></td>
                        <td class='left'><?php echo $client; ?></td>
                        <td></td>
                        <td class='right'><b>DATE SAMPLED:</b></td>
                        <td class='left'><?php echo $sampleDate; ?></td>
                    </tr>
                    <tr>
                        <td class='right'><b>ADDRESS:</b></td>
                        <td class='left'><?php echo $address; ?></td>
                        <td></td>
                        <td class='right'><b>LAB NUMBER:</b></td>
                        <td class='left'><?php echo $labNo; ?></td>
                    </tr>
                    <tr>
                        <td class='right'><b> </b></td>
                        <td class='left'><?php echo $state; ?></td>
                        <td></td>
                        <td class='right'><b>CROP:</b></td>
                        <td class='left'><?php echo $crop; ?></td>
                    </tr>
                    <tr>
                        <td class='right'><b> </b></td>
                        <td class='left'><?php echo $email; ?></td>
                        <td></td>
                        <td class='right'></td>
                        <td class='left'></td>
                    </tr>
                </tbody>
            </table>

            <!-- Graph Button -->
            <div class="d-print-none">
                <div class="row p-2">
                    <div class="col">
                        <button type="button" class="btn btn-primary" onclick="generateGraph()">
                            <i class="fas fa-chart-bar"></i> Generate Graph
                        </button>
                    </div>
                    <div class="col">
                        <div class="form-status-holder"></div>
                    </div>
                </div>
            </div>
            <!-- GRAPH BANNER -->

            <div class="row">
                <div class="col-md-12 text-center fw-bold h4">Soil Analysis Summary</div>
            </div>


            <!-- CHART HEADER  -->

            <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="">
                    <?php
                    require_once __DIR__.'/../../lib/soil_calculations.php';
                    echo soilAnalysisReportCalcs('Ca', 'BS_ca_ppm', 'ca_ppm_min', 'ca_ppm_max', 'Calcium', 'kg', 'col', $record_id, $rand_id);
                    echo soilAnalysisReportCalcs('Mg', 'BS_mg_ppm', 'mg_ppm_min', 'mg_ppm_max', 'Magnesium', 'kg', 'col', $record_id, $rand_id);
                    echo soilAnalysisReportCalcs('K', 'BS_k_ppm', 'k_ppm_min', 'k_ppm_max', 'Potasium', 'kg', 'col', $record_id, $rand_id);
                    echo soilAnalysisReportCalcs('Na', 'BS_na_ppm', 'na_ppm_min', 'na_ppm_max', 'Sodium', 'kg', 'col', $record_id, $rand_id);
                    echo soilAnalysisReportCalcs('P', 'p_colwell', '', '', 'Phosphate', 'kg', 'col', $record_id, $rand_id);
                    echo soilAnalysisReportCalcs('S', 's_morgan', '', '', 'Sulfur', 'kg', 'col', $record_id, $rand_id);
                    echo soilAnalysisReportCalcs('Mn', 'mn_dtpa', '', '', 'Manganese', 'kg', 'col', $record_id, $rand_id);
                    echo soilAnalysisReportCalcs('Fe', 'fe_dtpa', '', '', 'Iron', 'kg', 'col', $record_id, $rand_id);
                    echo soilAnalysisReportCalcs('Zn', 'zn_dtpa', '', '', 'Zinc', 'kg', 'col', $record_id, $rand_id);
                    echo soilAnalysisReportCalcs('Cu', 'cu_dtpa', '', '', 'Copper', 'kg', 'col', $record_id, $rand_id);
                    echo soilAnalysisReportCalcs('AmN', 'NH3_N', '', '', 'AmNitrogen', 'kg', 'col', $record_id, $rand_id);
                    echo soilAnalysisReportCalcs('B', 'b_cacl2', '', '', 'Boron', 'kg', 'col', $record_id, $rand_id);
                    echo soilAnalysisReportCalcs('NN', 'NO3_N', '', '', 'NNitrogen', 'kg', 'col', $record_id, $rand_id);
                    ?>
                </div>
            </div>

            <hr>

            <!-- **************** START OF FORM DATA **************** -->
            <form class="report-form" method="post">

                <input type="hidden" name="record_id" value="<?php echo htmlspecialchars($record_id, ENT_QUOTES, 'UTF-8'); ?>">
                <input type="hidden" name="rand_id" value="<?php echo htmlspecialchars($rand_id, ENT_QUOTES, 'UTF-8'); ?>">

                <!-- **************** OVERVIEW SECTION **************** -->
                <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="">
                    <?php
                    // Generate 5-year soil balancing program
                    for ($year = 1; $year <= 5; $year++) {
                        echo soilProgramCalcs('Ca', 'BS_ca_ppm', 'ca_ppm_min', 'ca_ppm_max', 'Calcium', 'kg', $record_id, $rand_id);
                    }
                    ?>
                </div> 

                <hr>

                <!-- **************** FOLIAR PROGRAM SECTION **************** -->
                <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>

                <!-- **************** MICROBE PROGRAM SECTION **************** -->
                <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">
                    <p style="font-style: italic; font-size: 9px;">Any recommendations provided by Cropmonitor are advice only, We are not paid consultants and we are not covered to accept responsibiliy for any of our suggestions. As no control can be exercised over storage, handling, mixing application or use, or weather, plant or soil conditions before, during or after application (all of which may affect the preformance of our program), no responsibility for, or liability for any failure in performance, losses, damage or injuries consequential or otherwise, arisiing form such storage mixng application or use will be accepted under any circumstances whatsoever. The buyer assumes all responsibility for the use of any of our products.</p>
                </div>

            </form>
        </div>
    </main>

    <footer class="py-4 bg-light mt-auto">
        <div class="container-fluid px-4">
            <div class="d-flex align-items-center justify-content-between small">
                <div class="text-muted">&copy; <?= date('Y') ?> Crop Management Platform. All Rights Reserved.</div>
                <div><a href="/privacy-policy.php">Privacy Policy</a> &middot; <a href="/terms.php">Terms &amp; Conditions</a></div>
            </div>
        </div>
    </footer>
</div>
</div>

<?php include __DIR__.'/../../layouts/footer.php'; ?>

<script>
function generateGraph() {
    alert('Graph generation functionality will be implemented here.');
}

$(document).ready(function(){
    var timeoutId;
                $('form textarea, form input').on('input propertychange change', function() {
                    console.log('Textarea Change');

                    clearTimeout(timeoutId);
                    timeoutId = setTimeout(function() {
                        // Runs 1 second (1000 ms) after the last change    
                        saveToDB();
                    }, 1000);
                });

                function saveToDB() {
                    console.log('Saving to the db');
                    form = $('.report-form');
                    $.ajax({
                        url: "/controllers/save_soil_analysis.php",
                        type: "POST",
                        data: form.serialize(), // serializes the form's elements.
                        beforeSend: function(xhr) {
                            // Let them know we are saving
                            $('.form-status-holder').html('Saving...');
                        },
                        success: function(data) {
                            var jqObj = jQuery(data); // You can get data returned from your ajax call here. ex. jqObj.find('.returned-data').html()
                            // Now show them we saved and when we did
                            var d = new Date();
                            $('.form-status-holder').html('Saved! Last: ' + d.toLocaleTimeString());
                        },
                    });
                }

                // This is just so we don't go anywhere  
                // and still save if you submit the form
                $('.report-form').submit(function(e) {
                    saveToDB();
                    e.preventDefault();
                });
            });
</script>
            