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

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

requireLogin();

$pageTitle = 'Plant Recommendations';
$siteName  = 'Crop Monitor';

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

// Handle image upload
if (isset($_POST['insert']) && isset($_FILES['image'])) {
    $file = file_get_contents($_FILES['image']['tmp_name']);
    if ($file !== false) {
        $stmt = $pdo->prepare('INSERT INTO plant_images (name) VALUES (?)');
        $stmt->execute([$file]);
    }
}

// Fetch distinct plant types for this user
$stmt = $pdo->prepare(
    'SELECT DISTINCT plant_type FROM plant_specifications WHERE modx_user_id = ? ORDER BY plant_type ASC'
);
$stmt->execute([$userId]);
$plantTypes = $stmt->fetchAll(\PDO::FETCH_COLUMN);

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

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">
                <h1 class="mt-4"><?= $h($pageTitle) ?></h1>
                <ol class="breadcrumb mb-4">
                    <li class="breadcrumb-item"><a href="/dashboard/dashboard.php">Dashboard</a></li>
                    <li class="breadcrumb-item active">Plant Recommendations</li>
                </ol>

                <div class="row">
                    <div class="col-12">
                        <h5>Plant Analysis</h5>
                        <p class="text-muted">Variables used in Plant Analysis recommendation programs.</p>

                        <div class="row mb-3">
                            <div class="col-md-4">
                                <select id="plantType" class="form-select">
                                    <option value="" selected>Select Plant Type</option>
                                    <?php foreach ($plantTypes as $pt): ?>
                                        <option value="<?= $h($pt) ?>"><?= $h($pt) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <div id="plantSpecsDisplay"></div>

                        <hr>
                        <p class="text-muted small">To add plant specification ranges, please contact your administrator or use the database management tools.</p>
                    </div>
                </div>
            </div>
        </main>

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

<script>
document.getElementById('plantType').addEventListener('change', function () {
    var plant = this.value;
    if (!plant) {
        document.getElementById('plantSpecsDisplay').innerHTML = '';
        return;
    }
    fetch('/dashboard/crop-analysis/plant-test-data/plant-rec-update.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'empid=' + encodeURIComponent(plant)
    })
    .then(function (r) { return r.text(); })
    .then(function (html) {
        document.getElementById('plantSpecsDisplay').innerHTML = html;
    });
});
</script>
