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

$pageTitle = 'Product List';
$siteName  = 'Crop Monitor';

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

$stmt = $pdo->prepare(
    'SELECT * FROM fertiliser_specifications WHERE modx_user_id = ? ORDER BY name ASC'
);
$stmt->execute([$userId]);
$products = $stmt->fetchAll();

$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">Product List</li>
                </ol>

                <div class="card mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span><i class="fas fa-flask me-1"></i>Company Product Analysis</span>
                        <button type="button" class="btn btn-success btn-sm"
                                data-bs-toggle="modal" data-bs-target="#addProductModal">
                            <i class="fas fa-plus me-1"></i>Add Product
                        </button>
                    </div>
                    <div class="card-body p-0">
                        <p class="text-muted px-3 pt-3 mb-0">Products used in Soil Analysis recommendation programs.</p>
                        <div class="table-responsive">
                            <table class="table table-bordered table-hover mb-0">
                                <thead class="table-dark">
                                    <tr>
                                        <th>ID</th><th>Product</th><th>Chemical</th>
                                        <th>N</th><th>P</th><th>K</th><th>Na</th><th>Ca</th><th>Mg</th>
                                        <th>B</th><th>Zn</th><th>Cu</th><th>Mn</th><th>Fe</th><th>Co</th><th>Mo</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <?php if (empty($products)): ?>
                                    <tr><td colspan="16" class="text-center text-muted">No products found.</td></tr>
                                <?php else: ?>
                                    <?php foreach ($products as $prod):
                                        $id = (int) $prod['id']; ?>
                                    <tr>
                                        <td><?= $id ?></td>
                                        <td><strong><?= $h($prod['name']) ?></strong></td>
                                        <td><?= $h($prod['chemical']) ?></td>
                                        <?php foreach (['n','p','k','Na','Ca','Mg','B','Zn','Cu','Mn','Fe','Co','Mo'] as $col): ?>
                                        <td contenteditable="true"
                                            onblur="updateDatabase(this,'<?= $h($col) ?>','<?= $id ?>')"
                                            onclick="showEdit(this)"><?= $h($prod[$col]) ?></td>
                                        <?php endforeach; ?>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

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

        </main>

        <!-- Add Product modal -->
        <div class="modal fade" id="addProductModal" tabindex="-1"
             aria-labelledby="addProductModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addProductModalLabel">Add New Product</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <form method="post" action="/controllers/newProductSubmit.php" id="newProductForm">
                        <div class="modal-body">
                            <input type="hidden" name="csrf_token"
                                   value="<?= $h(generateCsrfToken()) ?>">

                            <div class="row mb-3">
                                <div class="col">
                                    <label class="form-label">Product Name</label>
                                    <input type="text" class="form-control" name="name" required>
                                </div>
                                <div class="col">
                                    <label class="form-label">Chemical Symbol</label>
                                    <input type="text" class="form-control" name="chemical">
                                </div>
                            </div>

                            <div class="row row-cols-2 row-cols-md-4 g-2">
                                <?php foreach ([
                                    'N' => 'Nitrogen', 'P' => 'Phosphorus', 'K' => 'Potassium',
                                    'Na' => 'Sodium', 'Ca' => 'Calcium', 'Mg' => 'Magnesium',
                                    'B' => 'Boron', 'Zn' => 'Zinc', 'Cu' => 'Copper',
                                    'Mn' => 'Manganese', 'Fe' => 'Iron', 'Co' => 'Cobalt',
                                    'Mo' => 'Molybdenum',
                                ] as $col => $label): ?>
                                <div class="col">
                                    <label class="form-label form-label-sm"><?= $h($label) ?> — <?= $h($col) ?></label>
                                    <input type="number" step="0.01" class="form-control form-control-sm"
                                           name="<?= $h($col) ?>" value="0">
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-success">Save Product</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

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

<script>
function showEdit(el) {
    el.style.background = '#97e499';
}
function updateDatabase(el, column, id) {
    el.style.background = '#FDFDFD';
    fetch('/dashboard/client-settings/updateproduct.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'column=' + encodeURIComponent(column)
            + '&editval=' + encodeURIComponent(el.innerText.trim())
            + '&id=' + encodeURIComponent(id)
            + '&csrf_token=' + encodeURIComponent(
                document.querySelector('input[name="csrf_token"]').value
              )
    }).then(() => { el.style.background = 'white'; });
}
</script>
