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

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

if (!user_has_permission('orders')) {
    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;
}

$orders   = load_orders();
$clients  = load_clients();
$products = load_products();

$id = (int)($_GET['id'] ?? 0);
list($idx, $order) = find_order_by_id($orders, $id);

if ($order === null) {
    header('Location: orders.php');
    exit;
}

$err = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $po        = trim($_POST['po'] ?? '');
    $client    = trim($_POST['client'] ?? '');
    $ship_date = trim($_POST['ship_date'] ?? '');
    $product   = trim($_POST['product'] ?? '');
    $qty       = (int)($_POST['qty'] ?? 0);
    $notes     = trim($_POST['notes'] ?? '');

    if ($po === '' || $client === '' || $ship_date === '' || $product === '' || $qty <= 0) {
        $err = "PO, client, ship date, product and quantity are required.";
    } else {
        $orders[$idx]['po']        = $po;
        $orders[$idx]['client']    = $client;
        $orders[$idx]['ship_date'] = $ship_date;
        $orders[$idx]['product']   = $product;
        $orders[$idx]['qty']       = $qty;
        $orders[$idx]['notes']     = $notes;
        save_orders($orders);

        if ($client !== '' && !in_array($client, $clients, true)) {
            $clients[] = $client;
            save_clients($clients);
        }
        if ($product !== '' && !in_array($product, $products, true)) {
            $products[] = $product;
            save_products($products);
        }

        header('Location: orders.php');
        exit;
    }
}

include '../includes/header.php';
include '../includes/sidebar.php';
?>
<div class="container-fluid py-4">
  <h3 class="mb-3">Edit Order #<?= (int)$order['id'] ?></h3>
  <?php if ($err): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($err) ?></div>
  <?php endif; ?>

  <form method="post" class="card p-4" style="max-width:720px;">
    <div class="row g-3">
      <div class="col-md-4">
        <label class="form-label">PO</label>
        <input type="text" name="po" class="form-control" required
               value="<?= htmlspecialchars($order['po'] ?? '') ?>">
      </div>

      <div class="col-md-4">
        <label class="form-label">Client</label>
        <div class="input-group">
          <select name="client" class="form-select" id="client_select">
            <option value="">-- Select client --</option>
            <?php foreach ($clients as $c): ?>
              <option value="<?= htmlspecialchars($c) ?>"
                <?= (($order['client'] ?? '') === $c) ? 'selected' : '' ?>>
                <?= htmlspecialchars($c) ?>
              </option>
            <?php endforeach; ?>
          </select>
          <button class="btn btn-outline-secondary" type="button" onclick="addNewClient()">New</button>
        </div>
      </div>

      <div class="col-md-4">
        <label class="form-label">Ship date</label>
        <input type="date" name="ship_date" class="form-control" required
               value="<?= htmlspecialchars($order['ship_date'] ?? '') ?>">
      </div>

      <div class="col-md-6">
        <label class="form-label">Product</label>
        <div class="input-group">
          <select name="product" class="form-select" id="product_select">
            <option value="">-- Select product --</option>
            <?php foreach ($products as $p): ?>
              <option value="<?= htmlspecialchars($p) ?>"
                <?= (($order['product'] ?? '') === $p) ? 'selected' : '' ?>>
                <?= htmlspecialchars($p) ?>
              </option>
            <?php endforeach; ?>
          </select>
          <button class="btn btn-outline-secondary" type="button" onclick="addNewProduct()">New</button>
        </div>
      </div>

      <div class="col-md-2">
        <label class="form-label">Quantity</label>
        <input type="number" name="qty" class="form-control" min="1" required
               value="<?= (int)($order['qty'] ?? 0) ?>">
      </div>

      <div class="col-md-12">
        <label class="form-label">Notes</label>
        <textarea name="notes" class="form-control" rows="3"><?= htmlspecialchars($order['notes'] ?? '') ?></textarea>
      </div>
    </div>

    <button class="btn btn-primary mt-3">Save Changes</button>
    <a href="orders.php" class="btn btn-secondary mt-3">Cancel</a>
  </form>
</div>

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

<script>
function addNewClient() {
    const name = prompt("New client name:");
    if (!name) return;
    const select = document.getElementById('client_select');
    const opt = document.createElement('option');
    opt.value = name;
    opt.textContent = name;
    opt.selected = true;
    select.appendChild(opt);
}

function addNewProduct() {
    const name = prompt("New product name:");
    if (!name) return;
    const select = document.getElementById('product_select');
    const opt = document.createElement('option');
    opt.value = name;
    opt.textContent = name;
    opt.selected = true;
    select.appendChild(opt);
}
</script>
