<?php
require_once __DIR__.'/../../config/database.php';
require_once __DIR__.'/../../lib/auth.php';
require_once __DIR__.'/../../lib/validation.php';
require_once __DIR__.'/../../lib/soil_calculations.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);

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 = ?");
    $stmt->execute([$record_id, $rand_id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

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

    $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-report.php: " . $e->getMessage());
    die('Database error occurred');
}

$today = date('jS F Y');
$pageTitle = 'Soil Report - ' . ($client ?: 'Crop Monitoring');
$siteName = 'Crop Management Platform';
$activeItem = 'Soil Report';

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"> 
 <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" rel="stylesheet" type="text/css" />
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.css" integrity="sha256-PF6MatZtiJ8/c9O9HQ8uSUXr++R9KBYu4gbNG5511WE=" crossorigin="anonymous" rel="stylesheet" type="text/css"  />

<link type="text/css" href="/client-assets/weather-icons/css/weather-icons.min.css?version=1.16" rel="stylesheet" type="text/css" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/magnific-popup.css" rel="stylesheet" type="text/css" />

<script type="text/javascript" src="https://use.fontawesome.com/1e2844bb90.js"></script>
		
		<link href="/client-assets/css/dashboard.css" rel="stylesheet" type="text/css" />
		<script src="https://unpkg.com/gijgo@1.9.11/js/gijgo.min.js" type="text/javascript"></script>
		<link href="https://unpkg.com/gijgo@1.9.11/css/gijgo.min.css" rel="stylesheet" type="text/css" />
		<script src="client-assets/js/skycons.js" type="text/javascript"></script>
    
        <link href="client-assets/home/css/graphing.css" rel="stylesheet" type="text/css" media="screen" />
        <link href="client-assets/home/css/alux.min.css" rel="stylesheet" type="text/css" media="screen" />
        
        <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;
                }
                @page :left {
                    margin-left: 0.5cm;
                }
                @page :right {
                    margin-right: 0.5cm;
                }
                @page :top {
                    margin-top: 0cm;
                }
                @page :bottom {
                    margin-bottom: 0cm;
                }
            }
        </style>

    </head>
<body>
<div class="container">
    <div class="row">
        <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">
            <h4 class="mt-2">Soil Analysis for <?php echo $client; ?></h4>
            <p><strong>Sample:</strong> <?php echo $sample; ?> | <strong>Date:</strong> <?php echo $sampleDate; ?></p>
        </div>
    </div>

    <!-- display client metadata -->
    <div class="row">
        <div class="col-md-12">
            <table class="table table-sm table-borderless">
                <tr><th>Address</th><td><?php echo $address; ?></td><th>State/Postcode</th><td><?php echo $state; ?></td></tr>
                <tr><th>Email</th><td><?php echo $email; ?></td><th>Lab Number</th><td><?php echo $labNo; ?></td></tr>
                <tr><th>Crop</th><td><?php echo $crop; ?></td><th>Test Date</th><td><?php echo $sampleDate; ?></td></tr>
            </table>
        </div>
    </div>

    <!-- Graph Button -->
    <div class="d-print-none">
        <div class="row p-2">
            <div class="col">
                [[!soilAnalysisGraphButton]]
            </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 font-weight-bold h4">Soil Analysis Summary</div>
    </div>

    
    <!-- Element Required Module  -->
    <div class="element-required-module">
        <div class="alert alert-secondary" role="alert">
            <div class="text-center h5">Total kilograms per hectare of each element needed to balance soil in this test</div>
        </div>
        <div class="card-group">
            <?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);
            ?>
    <form class="report-form" method="post">
        <input class="" hidden type="text" name="id" id="id" value="[[+modx.user.id]]" >
    
        <!-- Overview Module  -->
        <div class="overview-module py-2">
            <div class="alert alert-secondary" role="alert">
                <div class="text-center h5">Overview</div>
            </div>
            <textarea id="overview" name="overview" >This is some text within a card body.</textarea>
        </div>
        
        <!-- Overview Module  -->
        <div class="overview-module py-2">
            <div class="alert alert-secondary" role="alert">
                <div class="text-center h5">Ideal Soil Balancing Program for One Season of a FIVE YEAR Plan</div>
            </div>
            <div class="card">
                <div class="card-body">
                    <?php
                    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>
            </div>
        </div>

         
        <hr>

        <div class="row pt-4">
            <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>    



    <script type="text/javascript">
        $(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: "[[~58]]",
                		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>

</div>

    <!-- 
    <script src="https://cloud.tinymce.com/stable/tinymce.min.js?apiKey=xcotawi18mg1imp8im144buq68h9g3ndd3c9c8215w8qu3ld"></script>
    <script>
        tinymce.init({
            selector: 'textarea',
            menubar: false,
            toolbar: 'bold italic  | alignleft aligncenter alignright alignjustify | bullist numlist | removeformat',
            plugins: 'autosave',
            autosave_interval: '20s'
        });
    </script>
    -->
    
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>	

<script type="text/javascript">
    addEventListener("load", function() { 
        setTimeout(hideURLbar, 0);
    }, false);
    function hideURLbar(){ 
        window.scrollTo(0,1);
    }
</script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js" integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/jquery.magnific-popup.js"></script>
    
    <script>
        //https://github.com/eKoopmans/html2pdf.js
        $('.downloadPDF').click(function () {
        	var element = document.getElementById('content'); //document.createElement("body");
        	element.classList.remove('screen');
        	element.classList.add('print');
        	var opt = {
        		margin:       3,
        		filename:     'soil-analysis.pdf',
        		image:        { type: 'jpeg', quality: 1.0 },
        		html2canvas:  { scale: 2, letterRendering: true, windowWidth: 1024 },  //, windowWidth: 1024
        		jsPDF:        { orientation: 'portrait', unit: 'mm', format: 'a4', putOnlyUsedFonts: true, floatPrecision: 'smart', }
        	};
        	html2pdf()
        	    .from(element)
        	    .toPdf()
        	    .set(opt)
        	    .save()
        	    .then(function(){
        		    element.classList.remove('print');
        		    element.classList.add('screen');
        	});
        	
        });
    </script>
</body>
</html>