<?php
// bakikhata.php (updated UI + customer live-search for Add Transaction)
require 'header.php';
require 'db.php';

$msg = '';

if (isset($_GET['added'])) $msg = 'Transaction recorded successfully.';
if (isset($_GET['deleted'])) $msg = 'Record deleted and balance reversed.';
if (isset($_GET['error'])) $msg = htmlspecialchars($_GET['error']);

// ---- Handle POST (add transaction) with PRG pattern ----
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_tx') {
    $customer_id = intval($_POST['customer_id'] ?? 0);
    $type = (isset($_POST['type']) && $_POST['type'] === 'dilam') ? 'dilam' : 'pelam';
    $amount = floatval($_POST['amount'] ?? 0);
    $note = trim($_POST['note'] ?? '');

    if ($customer_id <= 0) {
        $msg = 'Select a customer.';
    } elseif ($amount <= 0) {
        $msg = 'Provide an amount greater than zero.';
    } else {
        $signed = ($type === 'dilam') ? $amount : -$amount;
        $conn->begin_transaction();
        try {
            $ins = $conn->prepare('INSERT INTO bakhi_records (customer_id, amount, type, note) VALUES (?,?,?,?)');
            if ($ins === false) throw new Exception('Prepare failed (insert): ' . $conn->error);
            $ins->bind_param('idss', $customer_id, $amount, $type, $note);
            if (!$ins->execute()) throw new Exception('Execute failed (insert): ' . $ins->error);
            $ins->close();

            $upd = $conn->prepare('UPDATE customers SET balance = balance + ? WHERE id = ?');
            if ($upd === false) throw new Exception('Prepare failed (update): ' . $conn->error);
            $upd->bind_param('di', $signed, $customer_id);
            if (!$upd->execute()) throw new Exception('Execute failed (update): ' . $upd->error);
            $upd->close();

            $conn->commit();

            header('Location: bakikhata.php?customer_id=' . $customer_id . '&added=1');
            exit;
        } catch (Exception $e) {
            $conn->rollback();
            $msg = 'Transaction failed: ' . $e->getMessage();
        }
    }
}

// ---- Handle delete (reverse balance and delete record) ----
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $delId = (int)$_GET['delete'];
    $row = $conn->query("SELECT * FROM bakhi_records WHERE id = {$delId}")->fetch_assoc();
    if ($row) {
        $conn->begin_transaction();
        try {
            $signed = ($row['type'] === 'dilam') ? floatval($row['amount']) : -floatval($row['amount']);
            $rev = -$signed;

            $upd = $conn->prepare('UPDATE customers SET balance = balance + ? WHERE id = ?');
            if ($upd === false) throw new Exception('Prepare failed (reverse update): ' . $conn->error);
            $upd->bind_param('di', $rev, $row['customer_id']);
            if (!$upd->execute()) throw new Exception('Execute failed (reverse update): ' . $upd->error);
            $upd->close();

            $del = $conn->prepare('DELETE FROM bakhi_records WHERE id = ?');
            if ($del === false) throw new Exception('Prepare failed (delete): ' . $conn->error);
            $del->bind_param('i', $delId);
            if (!$del->execute()) throw new Exception('Execute failed (delete): ' . $del->error);
            $del->close();

            $conn->commit();

            header('Location: bakikhata.php?customer_id=' . intval($row['customer_id']) . '&deleted=1');
            exit;
        } catch (Exception $e) {
            $conn->rollback();
            $msg = 'Delete failed: ' . $e->getMessage();
        }
    } else {
        $msg = 'Record not found.';
    }
}

// ---- Load customers for live-search (we'll output JSON-like data into page) ----
$customers = [];
$cRes = $conn->query("SELECT id, name, phone, balance FROM customers ORDER BY name");
if ($cRes) {
    while ($c = $cRes->fetch_assoc()) $customers[] = $c;
}

// ---- If customer selected, load their ledger ----
$customer_id = isset($_GET['customer_id']) ? intval($_GET['customer_id']) : 0;
$selected_customer = null;
$ledger = null;
if ($customer_id) {
    $selected_customer = $conn->query("SELECT * FROM customers WHERE id = {$customer_id}")->fetch_assoc();
    $ledgerStmt = $conn->prepare('SELECT id,amount,type,note,created_at FROM bakhi_records WHERE customer_id = ? ORDER BY created_at DESC, id DESC');
    if ($ledgerStmt) {
        $ledgerStmt->bind_param('i', $customer_id);
        $ledgerStmt->execute();
        $ledger = $ledgerStmt->get_result();
    }
}

// ---- Helper: escape for JS data attribute (simpler) ----
function esc_js($s){ return str_replace(["\n","\r","'"], ['\\n','\\r',"&#39;"], $s); }
?>
<style>
/* Modern card UI */
.container { max-width:1100px; margin:18px auto; padding:0 12px; font-family: Inter, system-ui, -apple-system, 'Segoe UI', Roboto, Arial; color:#0f172a; }
.card { background: #fff; border-radius:12px; padding:18px; box-shadow:0 10px 30px rgba(2,6,23,0.06); margin-bottom:18px; }
.header-row { display:flex; justify-content:space-between; align-items:center; gap:12px; flex-wrap:wrap; }
.h1 { font-size:20px; font-weight:700; }
.actions { display:flex; gap:8px; align-items:center; }

/* Add tx area */
.form-row { display:flex; gap:10px; align-items:center; flex-wrap:wrap; margin-top:12px; }
.input, select, textarea { padding:10px 12px; border:1px solid #e6e9ee; border-radius:10px; font-size:14px; }
.input.small { width:120px; }
.input.medium { width:220px; }
.btn { padding:10px 14px; border-radius:10px; border:none; cursor:pointer; font-weight:600; }
.btn.primary { background:#0ea5a4; color:#fff; box-shadow:0 6px 18px rgba(14,165,164,0.12); }
.btn.ghost { background:transparent; border:1px solid #e6e9ee; color:#0f172a; }

/* live-search dropdown */
.search-wrap { position:relative; min-width:320px; }
.search-input { width:100%; box-sizing:border-box; }
.suggestions { position:absolute; left:0; right:0; background:#fff; border:1px solid #e6e9ee; border-radius:8px; margin-top:6px; max-height:240px; overflow:auto; z-index:30; box-shadow:0 8px 20px rgba(2,6,23,0.06); }
.suggestion { padding:8px 10px; cursor:pointer; display:flex; justify-content:space-between; gap:8px; align-items:center; }
.suggestion:hover, .suggestion.active { background:#f1f5f9; }

/* ledger table */
.ledger { margin-top:18px; border-radius:8px; overflow:hidden; border:1px solid #eef2f7; }
.ledger .row { display:flex; gap:12px; align-items:center; padding:10px 12px; background:#fff; border-bottom:1px solid #f3f4f6; }
.ledger .row.header { background:#f8fafc; font-weight:600; color:#0f172a; }
.col { flex:1; min-width:120px; }
.col.narrow { flex:0 0 150px; text-align:right; }
.small-muted { color:#6b7280; font-size:13px; }
.empty { padding:16px; color:#6b7280; }

/* responsive */
@media (max-width:800px){ .form-row { flex-direction:column; align-items:stretch; } .search-wrap{ min-width:100% } .col.narrow{ text-align:left } }
</style>

<div class="container">
  <div class="card">
    <div class="header-row">
      <div>
        <div class="h1">বাকি-খাতা (Ledger)</div>
        <div class="small-muted">Customer baki যোগ/কম করুন — search করে দ্রুত গ্রাহক বেছে নিন</div>
      </div>

      <div class="actions">
        <a href="add-customer.php" class="btn ghost" style="text-decoration:none">+ Add Customer</a>
        <a href="my-customer.php" class="btn ghost" style="text-decoration:none">📋 My Customers</a>
        <button onclick="window.print()" class="btn ghost">Print</button>
      </div>
    </div>

    <?php if ($msg): ?>
      <div style="margin-top:12px;color:#065f46;background:#ecfdf5;border:1px solid #bbf7d0;padding:10px;border-radius:8px"><?php echo htmlspecialchars($msg) ?></div>
    <?php endif; ?>

    <!-- Add transaction form (live customer search) -->
    <div class="form-row" style="margin-top:16px;">
      <form id="addTxForm" method="post" style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;width:100%;">
        <input type="hidden" name="action" value="add_tx">
        <input type="hidden" name="customer_id" id="customer_id_hidden" value="">

        <div class="search-wrap">
          <input id="customer_search" class="input search-input" placeholder="Search customer by name or phone..." autocomplete="off" />
          <div id="suggestions" class="suggestions" style="display:none"></div>
          <div class="small-muted" style="margin-top:6px">Select a customer (required) — type name or phone</div>
        </div>

        <select name="type" class="input small">
          <option value="dilam">Dilam — baki +</option>
          <option value="pelam">Pelam — baki -</option>
        </select>

        <input name="amount" type="number" step="0.01" class="input small" placeholder="Amount ৳" required>

        <input name="note" type="text" class="input medium" placeholder="Note (optional)">

        <button type="submit" class="btn primary">Save</button>
      </form>
    </div>

    <!-- Selected customer summary & ledger (if selected) -->
    <?php if ($customer_id && $selected_customer): ?>
      <div style="margin-top:18px;">
        <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap">
          <div>
            <div style="font-weight:700"><?php echo htmlspecialchars($selected_customer['name']) ?></div>
            <div class="small-muted">Phone: <?php echo htmlspecialchars($selected_customer['phone'] ?? '-') ?></div>
            <div class="small-muted">Joined: <?php echo htmlspecialchars($selected_customer['created_at'] ?? '') ?></div>
          </div>
          <div style="text-align:right">
            <div class="small-muted">Current Balance</div>
            <div style="font-size:20px;font-weight:700">৳ <?php echo number_format(floatval($selected_customer['balance']),2) ?></div>
          </div>
        </div>

        <div class="ledger">
          <div class="row header">
            <div class="col">Transaction</div>
            <div class="col">Note</div>
            <div class="col narrow">Date</div>
            <div class="col narrow">Lenden (Balance)</div>
            <div class="col narrow">Action</div>
          </div>

          <?php
          $running = floatval($selected_customer['balance']);
          if ($ledger && $ledger->num_rows):
            while ($r = $ledger->fetch_assoc()):
              $signed = ($r['type'] === 'dilam') ? floatval($r['amount']) : -floatval($r['amount']);
              $balance_after = $running;
              $running -= $signed;
          ?>
          <div class="row">
            <div class="col"><?php echo ($r['type']==='dilam' ? '+ ' : '- ') . number_format(floatval($r['amount']),2) ?></div>
            <div class="col"><?php echo htmlspecialchars($r['note']) ?></div>
            <div class="col narrow"><?php echo htmlspecialchars($r['created_at']) ?></div>
            <div class="col narrow">৳ <?php echo number_format($balance_after,2) ?></div>
            <div class="col narrow"><a href="bakikhata.php?delete=<?php echo (int)$r['id'] ?>" onclick="return confirm('Delete this record? This will reverse the balance change.')">Delete</a></div>
          </div>
          <?php
            endwhile;
          else:
          ?>
            <div class="row"><div class="col empty">No transactions yet for this customer.</div></div>
          <?php endif; ?>
        </div>
      </div>
    <?php else: ?>
     
    <?php endif; ?>

  </div>
</div>

<script>
// Client-side: customers data (from PHP)
const customers = <?php
    // output minimal safe JSON for client use
    $out = [];
    foreach ($customers as $c) {
        $out[] = [
            'id' => (int)$c['id'],
            'name' => $c['name'],
            'phone' => $c['phone'],
            'balance' => number_format(floatval($c['balance']),2)
        ];
    }
    echo json_encode($out, JSON_UNESCAPED_UNICODE);
?>;

const searchInput = document.getElementById('customer_search');
const suggestions = document.getElementById('suggestions');
const hiddenCustomerId = document.getElementById('customer_id_hidden');

let activeIndex = -1;
let filtered = [];

// Build display string for customer
function customerLabel(c){
  return c.name + (c.phone ? ' — ' + c.phone : '') + ' (৳' + c.balance + ')';
}

// Render suggestions list
function renderSuggestions(list){
  if (!list.length) { suggestions.style.display='none'; suggestions.innerHTML=''; return; }
  suggestions.innerHTML = '';
  list.forEach((c, idx) => {
    const div = document.createElement('div');
    div.className = 'suggestion';
    div.dataset.idx = idx;
    div.innerHTML = `<div style="font-weight:600">${escapeHtml(c.name)}</div><div class="small-muted" style="margin-left:12px">${escapeHtml(c.phone || '')} &nbsp; <span style="color:#0f172a;font-weight:700">৳ ${c.balance}</span></div>`;
    div.addEventListener('click', ()=> selectCustomer(idx));
    suggestions.appendChild(div);
  });
  suggestions.style.display = 'block';
  activeIndex = -1;
  highlightActive();
}

// Basic HTML escape
function escapeHtml(s){ return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }

// Filter customers by query
function filterCustomers(q){
  q = q.trim().toLowerCase();
  if (!q) return [];
  return customers.filter(c => {
    return (c.name && c.name.toLowerCase().includes(q)) || (c.phone && c.phone.toLowerCase().includes(q));
  });
}

// Select a customer from list
function selectCustomer(idx){
  const c = filtered[idx];
  if (!c) return;
  searchInput.value = customerLabel(c);
  hiddenCustomerId.value = c.id;
  suggestions.style.display='none';
  // focus amount input (nice UX)
  const amount = document.querySelector('input[name="amount"]');
  if (amount) amount.focus();
}

// keyboard navigation
function highlightActive(){
  const items = suggestions.querySelectorAll('.suggestion');
  items.forEach((it,i)=> it.classList.toggle('active', i===activeIndex));
}

searchInput.addEventListener('input', function(){
  hiddenCustomerId.value = ''; // clear hidden id when typing
  const q = this.value.trim();
  if (!q) { suggestions.style.display='none'; return; }
  filtered = filterCustomers(q);
  renderSuggestions(filtered);
});

searchInput.addEventListener('keydown', function(e){
  if (suggestions.style.display === 'block') {
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      activeIndex = Math.min(activeIndex + 1, filtered.length - 1);
      highlightActive();
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      activeIndex = Math.max(activeIndex - 1, 0);
      highlightActive();
    } else if (e.key === 'Enter') {
      e.preventDefault();
      if (activeIndex >= 0 && filtered[activeIndex]) {
        selectCustomer(activeIndex);
      } else {
        // if only one result, choose it
        if (filtered.length === 1) selectCustomer(0);
      }
    } else if (e.key === 'Escape') {
      suggestions.style.display='none';
    }
  }
});

// click outside to close suggestions
document.addEventListener('click', function(ev){
  if (!ev.target.closest('.search-wrap')) {
    suggestions.style.display='none';
  }
});

// form submit: ensure a customer is selected (hidden id must be set)
document.getElementById('addTxForm').addEventListener('submit', function(e){
  if (!hiddenCustomerId.value || hiddenCustomerId.value == '0') {
    e.preventDefault();
    alert('Please select a customer from the search results first.');
    searchInput.focus();
  }
});
</script>

<?php require 'footer.php'; ?>
