<?php
require 'header.php';
require 'db.php';

function h($s){ return htmlspecialchars((string)$s); }

// ensure uploads dir
$uploadDir = __DIR__ . '/uploads';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

$invoice_no = $_GET['invoice_no'] ?? ($_POST['invoice_no'] ?? '');
if (!$invoice_no) {
  echo "Invoice number required."; exit;
}

$errors = [];
$success = false;

/* --- Handle POST: update invoice --- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // collect fields
  $customer_name = trim($_POST['customer_name'] ?? '');
  $address = trim($_POST['address'] ?? '');
  $phone = trim($_POST['phone'] ?? '');
  $date = trim($_POST['date'] ?? '');
  $order_no = trim($_POST['order_no'] ?? '');
  $advance = floatval($_POST['advance'] ?? 0);

  // items arrays: desc[], qty[], item_weight[], price[], old_image[], remove_image[]
  $descs = $_POST['item_desc'] ?? [];
  $qtys  = $_POST['item_qty'] ?? [];
  $weights = $_POST['item_weight'] ?? [];
  $prices  = $_POST['item_price'] ?? [];
  $old_images = $_POST['old_image'] ?? [];
  $remove_images = $_POST['remove_image'] ?? []; // array of '1' for checked

  // files
  $fileNames = $_FILES['item_image']['name'] ?? [];
  $fileTmps  = $_FILES['item_image']['tmp_name'] ?? [];
  $fileErrs  = $_FILES['item_image']['error'] ?? [];
  $fileTypes = $_FILES['item_image']['type'] ?? [];

  // validate basic
  if ($customer_name === '') $errors[] = "Customer name required.";
  if ($date === '') $errors[] = "Date required.";

  // build items array
  $items = [];
  $total = 0.0;
  for ($i=0; $i < count($descs); $i++) {
    $desc = trim($descs[$i] ?? '');
    $qty = floatval($qtys[$i] ?? 0);
    // allow free-text weight; sanitize for storage
    $weight_raw = $weights[$i] ?? '';
    $weight = $conn->real_escape_string(trim((string)$weight_raw));
    $price = floatval($prices[$i] ?? 0);
    $old_img = $old_images[$i] ?? null;
    $remove = isset($remove_images[$i]) && $remove_images[$i] ? true : false;

    // skip empty rows (if totally empty)
    $noFileUploaded = empty($fileNames[$i]);
    if ($desc === '' && $qty == 0 && $price == 0 && $weight === '' && !$old_img && $noFileUploaded) continue;

    // handle uploaded file for this item (if any)
    $imagePath = null;
    // priority: if remove checked, delete old and ignore uploaded file
    if ($remove && $old_img) {
      // remove file on server if exists
      $serverPath = __DIR__ . '/' . ltrim($old_img, '/');
      if (file_exists($serverPath) && is_file($serverPath)) {
        @unlink($serverPath);
      }
      $old_img = null;
    }

    // if new file uploaded for this item
    if (isset($fileErrs[$i]) && $fileErrs[$i] === UPLOAD_ERR_OK && is_uploaded_file($fileTmps[$i])) {
      $finfo = @getimagesize($fileTmps[$i]);
      if ($finfo !== false) {
        $mime = $finfo['mime'];
        $allowed = ['image/jpeg'=>'jpg','image/png'=>'png','image/gif'=>'gif','image/webp'=>'webp'];
        if (isset($allowed[$mime])) {
          $ext = $allowed[$mime];
          $basename = bin2hex(random_bytes(8));
          $filename = $basename . '.' . $ext;
          $target = $uploadDir . '/' . $filename;
          if (move_uploaded_file($fileTmps[$i], $target)) {
            // if there was an old image, remove it now (we're replacing)
            if ($old_img) {
              $serverOld = __DIR__ . '/' . ltrim($old_img, '/');
              if (file_exists($serverOld) && is_file($serverOld)) @unlink($serverOld);
            }
            $imagePath = 'uploads/' . $filename;
          }
        } else {
          $errors[] = "Item #".($i+1)." - unsupported image type.";
        }
      } else {
        $errors[] = "Item #".($i+1)." - uploaded file is not a valid image.";
      }
    } else {
      // no new upload: keep old image unless removed
      $imagePath = $old_img ?: null;
    }

    // compute line total
    $line_total = $price * ($qty ?: 1);
    $total += $line_total;

    $items[] = [
      'desc' => $desc,
      'qty' => $qty,
      // store free-text weight under 'weight' for clarity
      'weight' => $weight,
      'price' => $price,
      'line_total' => round($line_total,2),
      'image' => $imagePath,
    ];
  }

  // compute totals
  $total = round($total,2);
  $balance = round($total - $advance,2);

  if (empty($errors)) {
    // update DB
    $items_json = json_encode($items, JSON_UNESCAPED_UNICODE);
    $stmt = $conn->prepare("UPDATE invoices SET customer_name=?, address=?, phone=?, date=?, order_no=?, items=?, total_amount=?, advance=? WHERE invoice_no = ? LIMIT 1");
    if ($stmt === false) {
      $errors[] = "DB prepare failed: " . $conn->error;
    } else {
      // types: s s s s s s d s s  -> customer_name, address, phone, date, order_no, items_json, total, advance, invoice_no
      $stmt->bind_param('ssssssdss', $customer_name, $address, $phone, $date, $order_no, $items_json, $total, $advance, $invoice_no);
      if ($stmt->execute()) {
        $success = true;
      } else {
        $errors[] = "DB update failed: " . $stmt->error;
      }
      $stmt->close();
    }
  }
}

/* --- Load invoice (fresh from DB) --- */
$stmt = $conn->prepare("SELECT * FROM invoices WHERE invoice_no = ? LIMIT 1");
if ($stmt === false) { echo "DB error"; exit; }
$stmt->bind_param('s', $invoice_no);
$stmt->execute();
$res = $stmt->get_result();
$inv = $res->fetch_assoc();
$stmt->close();
if (!$inv) { echo "Invoice not found: " . h($invoice_no); exit; }

// prefer POST values if just submitted (so form preserves submission) unless updated from DB
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $success) {
  // refresh $inv from DB after update
  $stmt = $conn->prepare("SELECT * FROM invoices WHERE invoice_no = ? LIMIT 1");
  $stmt->bind_param('s', $invoice_no);
  $stmt->execute();
  $res = $stmt->get_result();
  $inv = $res->fetch_assoc();
  $stmt->close();
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // use posted values to refill form on errors
  $inv['customer_name'] = $_POST['customer_name'] ?? $inv['customer_name'];
  $inv['address'] = $_POST['address'] ?? $inv['address'];
  $inv['phone'] = $_POST['phone'] ?? $inv['phone'];
  $inv['date'] = $_POST['date'] ?? $inv['date'];
  $inv['order_no'] = $_POST['order_no'] ?? $inv['order_no'];
  $inv['advance'] = $_POST['advance'] ?? $inv['advance'];
  // we'll rebuild items from POST below for display (so we don't trust inv['items'])
  $inv['items'] = json_encode([]);
}

// items for display
$items = json_decode($inv['items'], true);
if (!is_array($items)) $items = [];

// If POST with errors, rebuild items from POST so user doesn't lose input (and include images via old_image hidden fields)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$success) {
  $descs = $_POST['item_desc'] ?? [];
  $qtys  = $_POST['item_qty'] ?? [];
  $weights = $_POST['item_weight'] ?? [];
  $prices  = $_POST['item_price'] ?? [];
  $old_images = $_POST['old_image'] ?? [];
  $items = [];
  for ($i=0;$i<count($descs);$i++){
    $desc = trim($descs[$i]);
    $qty = floatval($qtys[$i] ?? 0);
    // preserve raw entered weight as string
    $weight = $conn->real_escape_string(trim((string)($weights[$i] ?? '')));
    $price = floatval($prices[$i] ?? 0);
    if ($desc=='' && $qty==0 && $weight=='' && $price==0 && empty($old_images[$i])) continue;
    $items[] = [
      'desc'=>$desc,
      'qty'=>$qty,
      // store under 'weight' so display uses free-text
      'weight'=>$weight,
      'price'=>$price,
      'line_total'=>round($price*($qty?:1),2),
      'image'=> !empty($old_images[$i]) ? $old_images[$i] : null,
    ];
  }
}

// helper to show flash
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Edit Invoice <?php echo h($invoice_no) ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body{font-family:Inter, 'SolaimanLipi', Arial, sans-serif;background:#f4f6f9;padding:20px;}
.container{max-width:1200px;margin:auto}
.card{box-shadow:0 8px 24px rgba(2,6,23,0.06)}
.table thead th{font-weight:800}
.input-sm{padding:.35rem .5rem}
.remove-row{cursor:pointer;color:#dc2626;font-weight:700}
.add-row{cursor:pointer;color:#0d6efd;font-weight:800}
.form-label{font-weight:700}
.thumb{max-width:64px;max-height:64px;border-radius:6px;overflow:hidden;border:1px solid #e6e9ef}
.thumb img{display:block;width:100%;height:100%;object-fit:cover}
.small-note{font-size:12px;color:#6b7280}
</style>
</head>
<body>
<div class="container">
  <div class="card p-4">
    <div class="d-flex align-items-center mb-3">
      <h3 class="me-auto">Edit Invoice: <?php echo h($invoice_no) ?></h3>
      <a class="btn btn-secondary me-2" href="invoice_search.php">Back to search</a>
      <a class="btn btn-success" href="print_invoice.php?invoice_no=<?php echo urlencode($invoice_no) ?>" target="_blank">View / Print</a>
    </div>

    <?php if ($success): ?>
      <div class="alert alert-success">Invoice updated successfully.</div>
    <?php endif; ?>

    <?php if ($errors): ?>
      <div class="alert alert-danger">
        <ul class="mb-0">
          <?php foreach($errors as $e): ?><li><?php echo h($e) ?></li><?php endforeach; ?>
        </ul>
      </div>
    <?php endif; ?>

    <!-- enctype for images -->
    <form method="post" id="editForm" enctype="multipart/form-data">
      <input type="hidden" name="invoice_no" value="<?php echo h($invoice_no) ?>">

      <div class="row g-3">
        <div class="col-md-6">
          <label class="form-label">Customer name</label>
          <input name="customer_name" class="form-control" value="<?php echo h($inv['customer_name'] ?? '') ?>">
        </div>
        <div class="col-md-3">
          <label class="form-label">Date</label>
          <input name="date" type="date" class="form-control" value="<?php echo h($inv['date'] ?? date('Y-m-d')) ?>">
        </div>
        <div class="col-md-3">
          <label class="form-label">Order No</label>
          <input name="order_no" class="form-control" value="<?php echo h($inv['order_no'] ?? '') ?>">
        </div>
        <div class="col-12">
          <label class="form-label">Address</label>
          <textarea name="address" class="form-control" rows="2"><?php echo h($inv['address'] ?? '') ?></textarea>
        </div>
        <div class="col-md-4">
          <label class="form-label">Phone</label>
          <input name="phone" class="form-control" value="<?php echo h($inv['phone'] ?? '') ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Advance</label>
          <input name="advance" type="number" step="0.01" class="form-control" id="advance" value="<?php echo h($inv['advance'] ?? 0) ?>">
        </div>
        <div class="col-md-4 d-flex align-items-end">
          <button type="button" id="addRow" class="btn btn-outline-primary">+ Add item</button>
        </div>
      </div>

      <hr>

      <div class="table-responsive">
        <table class="table table-bordered" id="itemsTable">
          <thead class="table-light">
            <tr>
              <th style="width:40%">বিবরণ</th>
              <th style="width:12%">ছবি</th>
              <th style="width:8%">Qty</th>
              <th style="width:12%">Wt (any)</th>
              <th style="width:14%">Price</th>
              <th style="width:10%">Line Total</th>
              <th style="width:4%"> </th>
            </tr>
          </thead>
          <tbody>
            <?php if (count($items)===0): ?>
              <tr>
                <td><input type="text" name="item_desc[]" class="form-control input-sm"></td>
                <td>
                  <div><input type="file" name="item_image[]" accept="image/*"></div>
                  <input type="hidden" name="old_image[]" value="">
                  <div class="small-note">Leave empty to keep</div>
                </td>
                <td><input type="number" name="item_qty[]" class="form-control input-sm qty" step="0.01" value="1"></td>
                <td><input type="text" name="item_weight[]" class="form-control input-sm" value=""></td>
                <td><input type="number" name="item_price[]" class="form-control input-sm price" step="0.01" value="0.00"></td>
                <td class="line-total text-end">0.00</td>
                <td class="text-center"><span class="remove-row">✖</span></td>
              </tr>
            <?php else: foreach($items as $idx=>$it):
              $img = $it['image'] ?? null;
              $imgAvailable = false;
              $imgUrl = '';
              if ($img) {
                $server = __DIR__ . '/' . ltrim($img, '/');
                if (file_exists($server) && is_file($server)) {
                  $imgAvailable = true;
                  $imgUrl = $img;
                } else {
                  // keep the path (maybe remote) but don't mark as available
                  $imgUrl = $img;
                }
              }
              // prefer new 'weight' (free-text), fallback to old numeric 'weight_g'
              $weightVal = isset($it['weight']) ? $it['weight'] : (isset($it['weight_g']) ? $it['weight_g'] : '');
            ?>
              <tr>
                <td><input type="text" name="item_desc[]" class="form-control input-sm" value="<?php echo h($it['desc']) ?>"></td>
                <td>
                  <?php if ($imgAvailable): ?>
                    <div class="thumb mb-1"><a href="<?php echo h($imgUrl) ?>" target="_blank"><img src="<?php echo h($imgUrl) ?>" alt=""></a></div>
                  <?php elseif ($img): ?>
                    <div class="small-note mb-1">Image path saved</div>
                  <?php else: ?>
                    <div class="small-note mb-1">— no image —</div>
                  <?php endif; ?>

                  <div><input type="file" name="item_image[]" accept="image/*"></div>
                  <input type="hidden" name="old_image[]" value="<?php echo h($img ?: '') ?>">
                  <?php if ($img): ?>
                    <div class="form-check">
                      <input class="form-check-input" type="checkbox" name="remove_image[<?php echo $idx ?>]" value="1" id="rm<?php echo $idx ?>">
                      <label class="form-check-label small-note" for="rm<?php echo $idx ?>">Remove image</label>
                    </div>
                  <?php endif; ?>
                </td>
                <td><input type="number" name="item_qty[]" class="form-control input-sm qty" step="0.01" value="<?php echo h($it['qty']) ?>"></td>
                <td><input type="text" name="item_weight[]" class="form-control input-sm" value="<?php echo h($weightVal) ?>"></td>
                <td><input type="number" name="item_price[]" class="form-control input-sm price" step="0.01" value="<?php echo h($it['price']) ?>"></td>
                <td class="line-total text-end"><?php echo number_format($it['line_total'] ?? ($it['price']*($it['qty']?:1)),2) ?></td>
                <td class="text-center"><span class="remove-row">✖</span></td>
              </tr>
            <?php endforeach; endif; ?>
          </tbody>
          <tfoot>
            <tr>
              <th colspan="5" class="text-end">মোট</th>
              <th class="text-end" id="grandTotal">0.00</th>
              <th></th>
            </tr>
          </tfoot>
        </table>
      </div>

      <div class="mt-3 d-flex gap-2">
        <button type="submit" class="btn btn-primary">Save changes</button>
        <a href="print_invoice.php?invoice_no=<?php echo urlencode($invoice_no) ?>" target="_blank" class="btn btn-success">Print</a>
        <a href="invoice_search.php" class="btn btn-secondary">Cancel</a>
      </div>
    </form>
  </div>
</div>

<script>
// helper to format number to 2 decimals
function fmt(n){ return Number(n||0).toFixed(2); }

// recalc line totals and grand total
function recalc(){
  let grand = 0;
  document.querySelectorAll('#itemsTable tbody tr').forEach(row=>{
    let qty = parseFloat(row.querySelector('.qty')?.value || 0) || 0;
    let price = parseFloat(row.querySelector('.price')?.value || 0) || 0;
    let line = price * (qty || 1);
    grand += line;
    row.querySelector('.line-total').textContent = fmt(line);
  });
  document.getElementById('grandTotal').textContent = fmt(grand);
}

// add row
document.getElementById('addRow').addEventListener('click', function(){
  const tbody = document.querySelector('#itemsTable tbody');
  const tr = document.createElement('tr');
  tr.innerHTML = `
    <td><input type="text" name="item_desc[]" class="form-control input-sm"></td>
    <td>
      <div><input type="file" name="item_image[]" accept="image/*"></div>
      <input type="hidden" name="old_image[]" value="">
      <div class="small-note">Leave empty to keep</div>
    </td>
    <td><input type="number" name="item_qty[]" class="form-control input-sm qty" step="0.01" value="1"></td>
    <td><input type="text" name="item_weight[]" class="form-control input-sm" value=""></td>
    <td><input type="number" name="item_price[]" class="form-control input-sm price" step="0.01" value="0.00"></td>
    <td class="line-total text-end">0.00</td>
    <td class="text-center"><span class="remove-row">✖</span></td>
  `;
  tbody.appendChild(tr);
  attachRowListeners(tr);
  recalc();
});

// attach listeners to existing rows
function attachRowListeners(row){
  row.querySelectorAll('.qty, .price').forEach(inp=>{
    inp.addEventListener('input', recalc);
  });
  const rem = row.querySelector('.remove-row');
  if (rem) rem.addEventListener('click', function(){ row.remove(); recalc(); });
}

// initialize listeners for existing rows
document.querySelectorAll('#itemsTable tbody tr').forEach(r=>attachRowListeners(r));
// recalc on load
recalc();

// optional: prevent accidental form double submit
document.getElementById('editForm').addEventListener('submit', function(){
  this.querySelector('button[type="submit"]').disabled = true;
});
</script>
</body>
</html>
