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

session_start();
if (!isset($_SESSION['user'])) { header('Location: /smproduce/auth/login.php'); exit; }
require_once __DIR__ . '/../config/users_local.php';
if (!user_has_permission('orders')) {
    http_response_code(403);
    echo "<h3>Access denied</h3>";
    exit;
}
require_once __DIR__ . '/../config/db_remote.php';

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    echo "Invalid order id.";
    exit;
}

$msg = "";
$err = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $po        = trim($_POST['po'] ?? '');
    $customer  = trim($_POST['customer'] ?? '');
    $product   = trim($_POST['product'] ?? '');
    $ship_date = trim($_POST['ship_date'] ?? '');
    $qty       = (int)($_POST['quantity'] ?? 0);
    $status    = trim($_POST['status'] ?? 'Open');
    $notes     = trim($_POST['notes'] ?? '');

    $allowedStatus = ['Open','Working On','Shipped'];
    if (!in_array($status, $allowedStatus, true)) {
        $status = 'Open';
    }

    if ($po === '' || $customer === '' || $product === '' || $ship_date === '' || $qty <= 0) {
        $err = "Please fill PO, Customer, Product, Ship Date and Quantity (>0).";
    } else {
        $poEsc        = $mysqli->real_escape_string($po);
        $customerEsc  = $mysqli->real_escape_string($customer);
        $productEsc   = $mysqli->real_escape_string($product);
        $shipEsc      = $mysqli->real_escape_string($ship_date);
        $notesEsc     = $mysqli->real_escape_string($notes);
        $statusEsc    = $mysqli->real_escape_string($status);

        $sql = "
            UPDATE orders
            SET po_number = '{$poEsc}',
                customer  = '{$customerEsc}',
                product   = '{$productEsc}',
                ship_date = '{$shipEsc}',
                quantity  = {$qty},
                status    = '{$statusEsc}',
                notes     = '{$notesEsc}'
            WHERE id = {$id}
            LIMIT 1
        ";
        if (!$mysqli->query($sql)) {
            $err = "Error updating order: " . $mysqli->error;
        } else {
            header("Location: /smproduce/pages/orders.php");
            exit;
        }
    }
}

// Load order for form
$res = $mysqli->query("SELECT * FROM orders WHERE id = {$id} LIMIT 1");
if (!$res || !$res->num_rows) {
    echo "Order not found.";
    exit;
}
$order = $res->fetch_assoc();

$po        = $order['po_number'] ?? '';
$customer  = $order['customer'] ?? '';
$product   = $order['product'] ?? '';
$ship_date = $order['ship_date'] ?? '';
$qty       = (int)($order['quantity'] ?? 0);
$status    = $order['status'] ?? 'Open';
$notes     = $order['notes'] ?? '';

$allowedStatus = ['Open','Working On','Shipped'];

include '../includes/header.php';
include '../includes/sidebar.php';
?>
<div class="container-fluid mt-3">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h3 class="mb-0">Edit Order #<?= (int)$order['id'] ?></h3>
    <a href="/smproduce/pages/orders.php" class="btn btn-sm btn-outline-secondary">← Back to Orders</a>
  </div>

  <?php if ($msg): ?>
    <div class="alert alert-success py-2"><?= htmlspecialchars($msg) ?></div>
  <?php endif; ?>
  <?php if ($err): ?>
    <div class="alert alert-danger py-2"><?= htmlspecialchars($err) ?></div>
  <?php endif; ?>

  <div class="card shadow-sm">
    <div class="card-header bg-white">
      <strong>Order details</strong>
    </div>
    <div class="card-body">
      <form method="post" class="row g-3">
        <div class="col-md-3">
          <label class="form-label">PO Number</label>
          <input type="text" name="po" class="form-control" value="<?= htmlspecialchars($po) ?>" required>
        </div>
        <div class="col-md-3">
          <label class="form-label">Customer</label>
          <input type="text" name="customer" class="form-control" value="<?= htmlspecialchars($customer) ?>" required>
        </div>
        <div class="col-md-3">
          <label class="form-label">Product</label>
          <input type="text" name="product" class="form-control" value="<?= htmlspecialchars($product) ?>" required>
        </div>
        <div class="col-md-2">
          <label class="form-label">Ship Date</label>
          <input type="date" name="ship_date" class="form-control" value="<?= htmlspecialchars($ship_date) ?>" required>
        </div>
        <div class="col-md-1">
          <label class="form-label">Qty</label>
          <input type="number" name="quantity" class="form-control" min="1" step="1" value="<?= htmlspecialchars($qty) ?>" required>
        </div>
        <div class="col-md-3">
          <label class="form-label">Status</label>
          <select name="status" class="form-select">
            <?php foreach ($allowedStatus as $st): ?>
              <option value="<?= htmlspecialchars($st) ?>" <?= $status===$st ? 'selected' : '' ?>>
                <?= htmlspecialchars($st) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-12">
          <label class="form-label">Notes</label>
          <textarea name="notes" class="form-control" rows="3"><?= htmlspecialchars($notes) ?></textarea>
        </div>
        <div class="col-12">
          <button class="btn btn-primary">Save changes</button>
          <a href="/smproduce/pages/orders.php" class="btn btn-outline-secondary ms-2">Cancel</a>
        </div>
      </form>
    </div>
  </div>
</div>

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