<?php
require_once __DIR__ . '/../config/user_functions.php';

session_start();
if (!isset($_SESSION['user'])) { header('Location: /smproduce/auth/login.php'); exit; }

$role = $_SESSION['user']['role'] ?? 'viewer';
if (!in_array($role, ['admin','warehouse'])) { http_response_code(403); die('Forbidden'); }

require_once __DIR__ . '/../config/db_remote.php';

$group_id = intval($_GET['group_id'] ?? 0);
if ($group_id <= 0) die("Invalid group ID");

// Carico preset per dropdown
$growers = $mysqli->query("SELECT id, name FROM growers_list ORDER BY name ASC")->fetch_all(MYSQLI_ASSOC);
$varieties = $mysqli->query("SELECT id, name FROM varieties_list ORDER BY name ASC")->fetch_all(MYSQLI_ASSOC);
$types = $mysqli->query("SELECT id, name FROM bin_types_list ORDER BY name ASC")->fetch_all(MYSQLI_ASSOC);

// Carico dati del gruppo
$group = $mysqli->query("
    SELECT 
        MIN(gp.name) AS grower,
        MIN(vl.name) AS variety,
        MIN(tl.name) AS type,
        MIN(bi.lot) AS lot,
        MIN(bi.date) AS date
    FROM bins_ingresso bi
    LEFT JOIN growers_list gp ON bi.grower_id = gp.id
    LEFT JOIN varieties_list vl ON bi.variety_id = vl.id
    LEFT JOIN bin_types_list tl ON bi.type_id = tl.id
    WHERE bi.group_id = {$group_id}
")->fetch_assoc();

if (!$group) die("Group not found");

// Se invio POST → salvo modifiche
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $grower  = $mysqli->real_escape_string($_POST['grower']);
    $variety = $mysqli->real_escape_string($_POST['variety']);
    $type    = $mysqli->real_escape_string($_POST['type']);
    $lot     = $mysqli->real_escape_string($_POST['lot']);
    $date    = $mysqli->real_escape_string($_POST['date']);

    // Converti NAME → ID
    $g = $mysqli->query("SELECT id FROM growers_list WHERE name='$grower'")->fetch_assoc();
    $v = $mysqli->query("SELECT id FROM varieties_list WHERE name='$variety'")->fetch_assoc();
    $t = $mysqli->query("SELECT id FROM bin_types_list WHERE name='$type'")->fetch_assoc();

    $grower_id = $g['id'] ?? 0;
    $variety_id = $v['id'] ?? 0;
    $type_id = $t['id'] ?? 0;

    if ($grower_id && $variety_id && $type_id) {
        $mysqli->query("
            UPDATE bins_ingresso
            SET 
                grower_id = {$grower_id},
                variety_id = {$variety_id},
                type_id = {$type_id},
                lot = '{$lot}',
                date = '{$date}'
            WHERE group_id = {$group_id}
        ");

        header("Location: dumping_bins.php?updated=1");
        exit;
    }
}

include('../includes/header.php');
include('../includes/sidebar.php');
?>

<div class="container-fluid">
    <h3 class="mb-4">Edit Dumping Group #<?= $group_id ?></h3>

    <form method="post" class="card p-4 shadow-sm">

        <div class="row mb-3">

            <div class="col-md-3">
                <label class="form-label">Grower</label>
                <select name="grower" class="form-select">
                    <?php foreach ($growers as $g): ?>
                        <option <?= ($g['name'] == $group['grower'] ? "selected" : "") ?>>
                            <?= htmlspecialchars($g['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-3">
                <label class="form-label">Variety</label>
                <select name="variety" class="form-select">
                    <?php foreach ($varieties as $v): ?>
                        <option <?= ($v['name'] == $group['variety'] ? "selected" : "") ?>>
                            <?= htmlspecialchars($v['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-3">
                <label class="form-label">Type</label>
                <select name="type" class="form-select">
                    <?php foreach ($types as $t): ?>
                        <option <?= ($t['name'] == $group['type'] ? "selected" : "") ?>>
                            <?= htmlspecialchars($t['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-3">
                <label class="form-label">Lot</label>
                <input type="text" class="form-control" name="lot" value="<?= htmlspecialchars($group['lot']) ?>">
            </div>
        </div>

        <div class="row mb-3">
            <div class="col-md-3">
                <label class="form-label">Date</label>
                <input type="date" class="form-control" name="date"
                       value="<?= htmlspecialchars($group['date']) ?>">
            </div>
        </div>

        <button class="btn btn-success">Save Changes</button>
        <a href="dumping_bins.php" class="btn btn-secondary">Cancel</a>

    </form>
</div>

<?php include('../includes/footer.php'); ?>
