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

if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once __DIR__ . '/../config/users_local.php';

if (!user_has_permission('settings')) {
    http_response_code(403);
    include '../includes/header.php';
    include '../includes/sidebar.php';
    echo "<div class='container-fluid py-4'><h3 class='text-danger'>Access denied</h3></div>";
    include '../includes/footer.php';
    exit;
}

$settingsFile = __DIR__ . '/../config/production_settings.json';

// default config if file does not exist
if (!file_exists($settingsFile)) {
    $default = [
        'visible_fields' => [
            'serial'      => true,  // from barcode_readings.code
            'SKU'         => true,
            'crop'        => true,
            'variety'     => true,
            'packaging'   => true,
            'size'        => true,
            'grower'      => true,
            'DateTime'    => true,
            'shipment_id' => true,
            'pallet_id'   => true,
            'operator'    => true,
            'station'     => true,
            'note'        => false,
            'read_time'   => true,
        ],
        'charts' => [
            'hourly'     => true,
            'daily'      => true,
            'monthly'    => true,
            'cumulative' => true,
        ],
        'refresh_interval' => 5,
        'rows_limit'       => 50,
    ];
    file_put_contents($settingsFile, json_encode($default, JSON_PRETTY_PRINT));
}

$cfg = json_decode(file_get_contents($settingsFile), true);
if (!is_array($cfg)) $cfg = [];

$visible   = $cfg['visible_fields']    ?? [];
$charts    = $cfg['charts']            ?? [];
$refresh   = (int)($cfg['refresh_interval'] ?? 5);
$rowsLimit = (int)($cfg['rows_limit']       ?? 50);

$message = '';

// handle POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $allFields = [
        'serial', 'SKU', 'crop', 'variety', 'packaging',
        'size', 'grower', 'DateTime', 'shipment_id',
        'pallet_id', 'operator', 'station', 'note', 'read_time'
    ];

    $newVisible = [];
    foreach ($allFields as $f) {
        // serial is always enabled
        if ($f === 'serial') {
            $newVisible[$f] = true;
        } else {
            $newVisible[$f] = isset($_POST['f_' . $f]);
        }
    }

    $newCharts = [
        'hourly'     => isset($_POST['c_hourly']),
        'daily'      => isset($_POST['c_daily']),
        'monthly'    => isset($_POST['c_monthly']),
        'cumulative' => isset($_POST['c_cumulative']),
    ];

    $refresh   = max(1, (int)($_POST['refresh_interval'] ?? 5));
    $rowsLimit = max(1, (int)($_POST['rows_limit'] ?? 50));

    $cfg = [
        'visible_fields'    => $newVisible,
        'charts'            => $newCharts,
        'refresh_interval'  => $refresh,
        'rows_limit'        => $rowsLimit,
    ];

    file_put_contents($settingsFile, json_encode($cfg, JSON_PRETTY_PRINT));
    $visible = $newVisible;
    $charts  = $newCharts;

    $message = 'Production settings saved successfully.';
}

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

<div class="container-fluid py-4" style="max-width:900px">
  <h3 class="mb-3">Production Settings</h3>
  <p class="text-muted">
    Configure which fields and charts are visible in the <strong>Production Summary</strong> page.
  </p>

  <?php if ($message): ?>
    <div class="alert alert-success"><?= htmlspecialchars($message) ?></div>
  <?php endif; ?>

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

    <h5 class="mb-3">Visible fields</h5>
    <div class="row">
      <?php
      $fieldLabels = [
          'serial'      => 'Serial (barcode)',
          'SKU'         => 'SKU',
          'crop'        => 'Crop',
          'variety'     => 'Variety',
          'packaging'   => 'Packaging',
          'size'        => 'Size',
          'grower'      => 'Grower',
          'DateTime'    => 'Case Date/Time',
          'shipment_id' => 'Shipment ID',
          'pallet_id'   => 'Pallet ID',
          'operator'    => 'Operator (reader)',
          'station'     => 'Station',
          'note'        => 'Note',
          'read_time'   => 'Scan time',
      ];

      foreach ($fieldLabels as $key => $label):
          $checked = !empty($visible[$key]);
      ?>
        <div class="col-md-4 mb-2">
          <div class="form-check">
            <?php if ($key === 'serial'): ?>
              <input class="form-check-input" type="checkbox" id="f_<?= $key ?>" checked disabled>
              <input type="hidden" name="f_<?= $key ?>" value="1">
            <?php else: ?>
              <input class="form-check-input" type="checkbox"
                     id="f_<?= $key ?>" name="f_<?= $key ?>" <?= $checked ? 'checked' : '' ?>>
            <?php endif; ?>
            <label class="form-check-label" for="f_<?= $key ?>"><?= htmlspecialchars($label) ?></label>
          </div>
        </div>
      <?php endforeach; ?>
    </div>

    <hr class="my-4">

    <h5 class="mb-3">Charts</h5>

    <div class="form-check mb-2">
      <input class="form-check-input" type="checkbox" id="c_hourly" name="c_hourly"
             <?= !empty($charts['hourly']) ? 'checked' : '' ?>>
      <label class="form-check-label" for="c_hourly">Hourly production (today)</label>
    </div>

    <div class="form-check mb-2">
      <input class="form-check-input" type="checkbox" id="c_daily" name="c_daily"
             <?= !empty($charts['daily']) ? 'checked' : '' ?>>
      <label class="form-check-label" for="c_daily">Daily production (last 30 days)</label>
    </div>

    <div class="form-check mb-2">
      <input class="form-check-input" type="checkbox" id="c_monthly" name="c_monthly"
             <?= !empty($charts['monthly']) ? 'checked' : '' ?>>
      <label class="form-check-label" for="c_monthly">Monthly production (last 12 months)</label>
    </div>

    <div class="form-check mb-3">
      <input class="form-check-input" type="checkbox" id="c_cumulative" name="c_cumulative"
             <?= !empty($charts['cumulative']) ? 'checked' : '' ?>>
      <label class="form-check-label" for="c_cumulative">Cumulative production</label>
    </div>

    <hr class="my-4">

    <h5 class="mb-3">Live feed options</h5>

    <div class="mb-3">
      <label class="form-label" for="refresh_interval">Auto-refresh interval (seconds)</label>
      <input type="number" class="form-control" id="refresh_interval"
             name="refresh_interval" min="1" value="<?= (int)$refresh ?>">
      <div class="form-text">How often the production summary page refreshes automatically.</div>
    </div>

    <div class="mb-3">
      <label class="form-label" for="rows_limit">Max rows in live table</label>
      <input type="number" class="form-control" id="rows_limit"
             name="rows_limit" min="1" value="<?= (int)$rowsLimit ?>">
      <div class="form-text">Number of latest scans to show in the live table.</div>
    </div>

    <button class="btn btn-primary mt-2">Save Production Settings</button>

  </form>
</div>

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