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

$msg = '';

function h($s){ return htmlspecialchars((string)$s); }
function genInvoiceNo(){ return date('Ymd') . '-' . substr(str_shuffle('0123456789'),0,4); }

// Ensure upload dir exists
$uploadDir = __DIR__ . '/uploads';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $invoice_no = trim($_POST['invoice_no'] ?? '') ?: genInvoiceNo();
    $customer_name = $conn->real_escape_string($_POST['customer_name'] ?? '');
    $address = $conn->real_escape_string($_POST['address'] ?? '');
    $phone = $conn->real_escape_string($_POST['phone'] ?? '');
    $order_no = $conn->real_escape_string($_POST['order_no'] ?? '');
    $date = $_POST['date'] ?? date('Y-m-d');
    $advance = floatval($_POST['advance'] ?? 0.0);
    $theme = in_array($_POST['theme'] ?? 'A', ['A','B']) ? $_POST['theme'] : 'A';

    // items
    $items = [];
    $total = 0.0;
    $descs = $_POST['item_desc'] ?? [];
    $qtys = $_POST['item_qty'] ?? [];
    $wts = $_POST['item_wt'] ?? [];
    $prices = $_POST['item_price'] ?? [];

    // Prepare files arrays if any
    $fileNames = $_FILES['item_image']['name'] ?? [];
    $fileTmp = $_FILES['item_image']['tmp_name'] ?? [];
    $fileErr = $_FILES['item_image']['error'] ?? [];
    $fileType = $_FILES['item_image']['type'] ?? [];

    for ($i=0;$i<count($descs);$i++){
        $desc = trim($descs[$i] ?? '');
        if ($desc === '') continue;
        $qty = floatval($qtys[$i] ?? 0);
        // allow any text for weight; sanitize for safe storage
        $wt = $conn->real_escape_string(trim($wts[$i] ?? ''));
        $price = floatval($prices[$i] ?? 0);
        $line_total = round($qty * $price, 2);

        // handle image for this item (if uploaded)
        $imagePath = null;
        if (isset($fileErr[$i]) && $fileErr[$i] === UPLOAD_ERR_OK && is_uploaded_file($fileTmp[$i])) {
            // validate image
            $finfo = @getimagesize($fileTmp[$i]);
            if ($finfo !== false) {
                $mime = $finfo['mime']; // e.g. image/jpeg
                $allowed = ['image/jpeg'=>'jpg','image/png'=>'png','image/gif'=>'gif','image/webp'=>'webp'];
                if (isset($allowed[$mime])) {
                    $ext = $allowed[$mime];
                    // unique filename
                    $basename = bin2hex(random_bytes(8));
                    $filename = $basename . '.' . $ext;
                    $target = $uploadDir . '/' . $filename;
                    if (move_uploaded_file($fileTmp[$i], $target)) {
                        // store web-accessible path (adjust if your app is in subfolder)
                        $imagePath = 'uploads/' . $filename;
                    }
                }
            }
            // if validation fails, we silently ignore image; you can set $msg to notify user if wanted
        }

        $items[] = [
            'desc'=>$desc,
            'qty'=>$qty,
            'weight'=>$wt,       // now a string (any text)
            'price'=>$price,
            'line_total'=>$line_total,
            'image'=>$imagePath
        ];
        $total += $line_total;
    }
    $total = round($total,2);

    // insert
    $items_json = json_encode($items, JSON_UNESCAPED_UNICODE);
    $stmt = $conn->prepare('INSERT INTO invoices (invoice_no, customer_name, address, phone, order_no, date, advance, items, total_amount, theme) VALUES (?,?,?,?,?,?,?,?,?,?)');
    if ($stmt === false) {
        $msg = 'DB error: ' . $conn->error;
    } else {
        // types: s s s s s s d s d s  => 'ssssssdsds'
        $stmt->bind_param('ssssssdsds', $invoice_no, $customer_name, $address, $phone, $order_no, $date, $advance, $items_json, $total, $theme);
        if ($stmt->execute()) {
            header('Location: print_invoice.php?invoice_no=' . urlencode($invoice_no));
            exit;
        } else {
            $msg = 'Insert failed: ' . $stmt->error;
        }
        $stmt->close();
    }
}

?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Create Invoice</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
:root{
  --A-grad1: #7c2d91;
  --A-grad2: #f97316;
  --B-grad1: #2563eb;
  --B-grad2: #06b6d4;
  --muted: #6b7280;
}
body{font-family:Inter,'SolaimanLipi',Arial,sans-serif;background:#f9fafb;margin:0;padding:20px;color:#0f172a}
.container{max-width:1000px;margin:auto;background:#fff;border-radius:10px;padding:20px;box-shadow:0 8px 25px rgba(0,0,0,0.06);}
h2{margin-top:0;background:linear-gradient(90deg,var(--A-grad1),var(--A-grad2));-webkit-background-clip:text;-webkit-text-fill-color:transparent;}
input,textarea,select{width:100%;padding:8px;border:1px solid #e5e7eb;border-radius:6px;font-size:14px;box-sizing:border-box}
label{font-weight:600;font-size:14px;display:block;margin-bottom:5px}
.row{display:flex;gap:10px;margin-bottom:10px}
.btn{padding:8px 12px;border:none;border-radius:6px;font-weight:700;cursor:pointer}
.btn-save{background:linear-gradient(90deg,var(--A-grad1),var(--A-grad2));color:#fff;}
.btn-add{background:#06b6d4;color:#fff;}
.btn-remove{background:#f87171;color:#fff;}
.table{width:100%;border-collapse:collapse;margin-top:10px;}
.table th,.table td{border:1px solid #e5e7eb;padding:8px;text-align:center;font-size:14px}
.total-box{display:flex;justify-content:flex-end;margin-top:10px;font-size:16px;font-weight:700}
.theme-box{background:linear-gradient(90deg,var(--B-grad1),var(--B-grad2));padding:10px;color:#fff;border-radius:8px;font-weight:700;text-align:center;margin-bottom:12px}
</style>
</head>
<body>
<div class="container">
  <h2>🧾 Create New Invoice</h2>

  <?php if($msg): ?><p style="color:red"><?php echo h($msg) ?></p><?php endif; ?>

  <!-- enctype for file upload -->
  <form method="post" id="invoiceForm" enctype="multipart/form-data">
    <div class="row">
      <div><label>Invoice No</label><input name="invoice_no" value="<?php echo h(genInvoiceNo()); ?>"></div>
      <div><label>Date</label><input type="date" name="date" value="<?php echo h(date('Y-m-d')); ?>"></div>
      <div><label>Order No</label><input name="order_no"></div>
    </div>

    <div class="row">
      <div><label>Customer Name</label><input name="customer_name"></div>
      <div><label>Phone</label><input name="phone"></div>
    </div>

    <label>Address</label>
    <textarea name="address" rows="2"></textarea>

    <div class="row">
      <div><label>Advance (অগ্রিম)</label><input type="number" step="0.01" id="advance" name="advance" value="0"></div>
      <div><label>Theme</label>
        <select name="theme">
          <option value="A">🟣 বেগুনি ↔ কমলা</option>
          <option value="B">🔵 নীল ↔ আকাশি</option>
        </select>
      </div>
    </div>

    <h3>Items</h3>
    <table class="table" id="itemTable">
      <thead><tr><th>Description</th><th>Image</th><th>Qty</th><th>Weight (g)</th><th>Price</th><th>Total</th><th></th></tr></thead>
      <tbody>
        <tr>
          <td><input name="item_desc[]" required></td>
          <td><input name="item_image[]" type="file" accept="image/*"></td>
          <td><input name="item_qty[]" type="number" step="0.01" value="1"></td>
          <td><input name="item_wt[]" type="text" placeholder="e.g. 120 g / 0.12kg / approx 100"></td>
          <td><input name="item_price[]" type="number" step="0.01" value="0"></td>
          <td class="lineTotal">0.00</td>
          <td><button type="button" class="btn btn-add" onclick="addRow()">+</button></td>
        </tr>
      </tbody>
    </table>

    <div class="total-box">মোট টাকা: <span id="totalTk" style="margin-left:6px;">0.00</span></div>

    <div class="row">
      <div style="margin-left:auto;width:200px;">
        <label>বাকি (Due)</label>
        <input type="text" id="due" readonly style="font-weight:bold;">
      </div>
    </div>

    <div style="margin-top:12px;text-align:right">
      <button type="submit" class="btn btn-save">💾 Save & Print</button>
    </div>
  </form>
</div>

<script>
function addRow(){
  const row=`<tr>
    <td><input name="item_desc[]" required></td>
    <td><input name="item_image[]" type="file" accept="image/*"></td>
    <td><input name="item_qty[]" type="number" step="0.01" value="1"></td>
    <td><input name="item_wt[]" type="text" placeholder="e.g. 120 g / 0.12kg / approx 100"></td>
    <td><input name="item_price[]" type="number" step="0.01" value="0"></td>
    <td class="lineTotal">0.00</td>
    <td><button type="button" class="btn btn-remove" onclick="this.closest('tr').remove();calcTotal()">x</button></td>
  </tr>`;
  document.querySelector("#itemTable tbody").insertAdjacentHTML('beforeend',row);
}
document.addEventListener('input',calcTotal);
document.getElementById('advance').addEventListener('input',calcTotal);
function calcTotal(){
  let total=0;
  document.querySelectorAll("#itemTable tbody tr").forEach(tr=>{
    const qty=parseFloat(tr.querySelector('[name="item_qty[]"]').value)||0;
    const price=parseFloat(tr.querySelector('[name="item_price[]"]').value)||0;
    const line=qty*price;
    tr.querySelector('.lineTotal').innerText=line.toFixed(2);
    total+=line;
  });
  document.getElementById('totalTk').innerText=total.toFixed(2);
  const adv=parseFloat(document.getElementById('advance').value)||0;
  document.getElementById('due').value=(total-adv).toFixed(2);
}
// run once to initialize
calcTotal();
</script>
<?php require 'footer.php'; ?>
</body>
</html>
