<?php
/**
 * plant-rec-update.php
 *
 * Renders the plant specifications reference table for a given plant type.
 * Included by plant analysis pages — not a standalone page.
 * Requires auth.php and database.php to already be included.
 */

if (!function_exists('isLoggedIn')) {
    require_once __DIR__ . '/../../../lib/auth.php';
}
if (!function_exists('getDBConnection')) {
    require_once __DIR__ . '/../../../config/database.php';
}

requireLogin();

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

$plantType = trim($_REQUEST['empid'] ?? '');

if ($plantType === '') {
    echo '<p class="text-muted">No plant type specified.</p>';
    return;
}

// ── Plant specifications table ────────────────────────────────────────────
$stmt = $pdo->prepare('
    SELECT plant_stage,
           n_min, n_max, P_min, P_max, K_min, K_max, S_min, S_max,
           Ca_min, Ca_max, Mg_min, Mg_max, Na_min, Na_max,
           Cu_min, Cu_max, Zn_min, Zn_max, Mn_min, Mn_max,
           B_min, B_max, Fe_min, Fe_max,
           M_Min, M_Max, Co_min, Co_max, se_min, se_max, cl_min, cl_max
    FROM plant_specifications
    WHERE modx_user_id = ? AND plant_type = ?
');
$stmt->execute([$userId, $plantType]);
$specs = $stmt->fetchAll();

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

if (empty($specs)) {
    echo '<p class="text-muted">No specifications found for plant type: ' . $h($plantType) . '</p>';
} else {
    echo '<div class="table-responsive text-nowrap">';
    echo '<table class="table table-sm table-striped table-hover table-bordered">';
    echo '<thead><tr>';
    $cols = array_keys($specs[0]);
    foreach ($cols as $col) {
        $label = ucwords(str_replace('_', ' ', $col));
        echo '<th class="text-center text-capitalize">' . $h($label) . '</th>';
    }
    echo '</tr></thead><tbody>';

    foreach ($specs as $row) {
        echo '<tr>';
        foreach ($row as $key => $val) {
            $display = ($val === '' || $val === null) ? '0.0'
                : (is_numeric($val) ? number_format((float) $val, 2, '.', '') : $h($val));
            echo '<td class="text-center">' . $display . '</td>';
        }
        echo '</tr>';
    }
    echo '</tbody></table></div>';
}

// ── Plant images gallery ──────────────────────────────────────────────────
$imgStmt = $pdo->prepare('SELECT id, name FROM plant_images ORDER BY id DESC LIMIT 20');
$imgStmt->execute();
$images = $imgStmt->fetchAll();

if (!empty($images)) {
    echo '<div class="row mt-2">';
    foreach ($images as $img) {
        echo '<div class="col-auto">';
        echo '<img src="data:image/jpeg;base64,' . base64_encode($img['name']) . '" '
           . 'class="img-thumbnail border-success" style="max-width:120px;" alt="">';
        echo '</div>';
    }
    echo '</div>';
}

// ── Image upload form ─────────────────────────────────────────────────────
?>
<form method="post" enctype="multipart/form-data" class="mt-3">
    <div class="mb-2">
        <input type="file" class="form-control form-control-sm" name="image" id="image" accept="image/*">
    </div>
    <button type="submit" name="insert" id="insert" value="Insert" class="btn btn-info btn-sm">
        Upload Image
    </button>
</form>
