<?php
// -----------------------------
// my-customer.php  (updated UI + Deactivated button)
// - supports: list active customers, list inactive (trash), deactivate (soft-delete), reactivate, and permanent delete
// - IMPORTANT: ensure `customers` table has `active TINYINT(1) NOT NULL DEFAULT 1`.
//   Run once: ALTER TABLE customers ADD COLUMN active TINYINT(1) NOT NULL DEFAULT 1;
// -----------------------------

require 'db.php';

$msg = '';

function is_ajax() {
    return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
}

// --- Actions (unchanged behavior) ---
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $del = intval($_GET['delete']);
    $ajax = is_ajax();

    $stmt = $conn->prepare('UPDATE customers SET active = 0 WHERE id = ?');
    if ($stmt) {
        $stmt->bind_param('i', $del);
        if ($stmt->execute()) {
            if ($ajax) { while (ob_get_level()) ob_end_clean(); header('Content-Type: application/json'); echo json_encode(['success'=>true]); exit; }
            header('Location: my-customer.php?deleted=1'); exit;
        } else {
            $msg = 'Deactivate failed: ' . $stmt->error;
            if ($ajax) { while (ob_get_level()) ob_end_clean(); header('Content-Type: application/json'); echo json_encode(['success'=>false,'error'=>$msg]); exit; }
        }
        $stmt->close();
    } else {
        $msg = 'Prepare failed: ' . $conn->error;
        if ($ajax) { while (ob_get_level()) ob_end_clean(); header('Content-Type: application/json'); echo json_encode(['success'=>false,'error'=>$msg]); exit; }
    }
}

if (isset($_GET['reactivate']) && is_numeric($_GET['reactivate'])) {
    $rid = intval($_GET['reactivate']);
    $ajax = is_ajax();

    $stmt = $conn->prepare('UPDATE customers SET active = 1 WHERE id = ?');
    if ($stmt) {
        $stmt->bind_param('i', $rid);
        if ($stmt->execute()) {
            if ($ajax) { while (ob_get_level()) ob_end_clean(); header('Content-Type: application/json'); echo json_encode(['success'=>true]); exit; }
            header('Location: my-customer.php?reactivated=1'); exit;
        } else {
            $msg = 'Reactivate failed: ' . $stmt->error;
            if ($ajax) { while (ob_get_level()) ob_end_clean(); header('Content-Type: application/json'); echo json_encode(['success'=>false,'error'=>$msg]); exit; }
        }
        $stmt->close();
    } else {
        $msg = 'Prepare failed: ' . $conn->error;
        if ($ajax) { while (ob_get_level()) ob_end_clean(); header('Content-Type: application/json'); echo json_encode(['success'=>false,'error'=>$msg]); exit; }
    }
}

if (isset($_GET['permanent_delete']) && is_numeric($_GET['permanent_delete'])) {
    $pid = intval($_GET['permanent_delete']);
    $ajax = is_ajax();

    $return_json = function($arr) {
        while (ob_get_level()) ob_end_clean();
        header('Content-Type: application/json');
        echo json_encode($arr);
        exit;
    };

    $chk = $conn->prepare('SELECT active FROM customers WHERE id = ?');
    if (!$chk) {
        $err = 'Prepare failed: ' . $conn->error;
        if ($ajax) $return_json(['success'=>false,'error'=>$err]);
        $msg = $err;
    } else {
        $chk->bind_param('i', $pid);
        $chk->execute();
        $cres = $chk->get_result()->fetch_assoc();
        $chk->close();
        if (!$cres) {
            $err = 'Customer not found.';
            if ($ajax) $return_json(['success'=>false,'error'=>$err]);
            $msg = $err;
        } elseif (intval($cres['active']) === 1) {
            $err = 'Cannot permanently delete an active customer. Deactivate first.';
            if ($ajax) $return_json(['success'=>false,'error'=>$err]);
            $msg = $err;
        }
    }

    if (empty($msg)) {
        $conn->begin_transaction();
        try {
            $delLedger = $conn->prepare('DELETE FROM bakhi_records WHERE customer_id = ?');
            if (!$delLedger) throw new Exception('Prepare ledger-delete failed: ' . $conn->error);
            $delLedger->bind_param('i', $pid);
            $delLedger->execute();
            $ledgerAffected = $delLedger->affected_rows;
            $delLedger->close();

            $delCust = $conn->prepare('DELETE FROM customers WHERE id = ?');
            if (!$delCust) throw new Exception('Prepare customer-delete failed: ' . $conn->error);
            $delCust->bind_param('i', $pid);
            $delCust->execute();
            $custAffected = $delCust->affected_rows;
            $delCust->close();

            $conn->commit();

            if ($ajax) $return_json(['success'=>true, 'ledger_deleted'=>$ledgerAffected, 'customer_deleted'=>$custAffected]);
            header('Location: my-customer.php?permanently_deleted=1');
            exit;
        } catch (Exception $e) {
            $conn->rollback();
            $fullErr = $e->getMessage();
            if ($conn->errno === 1451) {
                $hint = 'Foreign key constraint prevents delete (related rows exist).';
            } else {
                $hint = '';
            }
            $errMsg = 'Delete failed: ' . $fullErr . ($hint ? ' — ' . $hint : '') . ' (DB errno: ' . $conn->errno . ')';
            if ($ajax) $return_json(['success'=>false,'error'=>$errMsg, 'raw_error'=>$fullErr]);
            $msg = $errMsg;
        }
    }
}

// --- compute number of deactivated customers for Trash badge ---
$inactive_count = 0;
$r = $conn->query('SELECT COUNT(*) as c FROM customers WHERE active = 0');
if ($r) {
    $rc = $r->fetch_assoc();
    $inactive_count = intval($rc['c'] ?? 0);
}

// -----------------------------
// After handlers: render page
// -----------------------------
require 'header.php';

if (isset($_GET['created'])) $msg = 'Customer created.';
if (isset($_GET['updated'])) $msg = 'Customer updated.';
if (isset($_GET['deleted'])) $msg = 'Customer deactivated.';
if (isset($_GET['reactivated'])) $msg = 'Customer reactivated.';
if (isset($_GET['permanently_deleted'])) $msg = 'Customer permanently deleted.';

$view = (isset($_GET['view']) && $_GET['view'] === 'inactive') ? 'inactive' : 'active';
$search = trim($_GET['q'] ?? '');
$params = [];
$types = '';
$filter_sql = ($view === 'active') ? ' WHERE active = 1' : ' WHERE active = 0';

if ($search !== '') {
    $like = '%' . $search . '%';
    $filter_sql .= ' AND (name LIKE ? OR phone LIKE ? OR address LIKE ?)';
    $types = 'sss';
    $params = [$like, $like, $like];
}

$total_balance = 0.0;
$tot_query = 'SELECT COALESCE(SUM(balance),0) as total FROM customers' . $filter_sql;
if ($types) {
    $tot_stmt = $conn->prepare($tot_query);
    $tot_stmt->bind_param($types, ...$params);
    $tot_stmt->execute();
    $tres = $tot_stmt->get_result()->fetch_assoc();
    $total_balance = floatval($tres['total'] ?? 0);
    $tot_stmt->close();
} else {
    $tres = $conn->query($tot_query);
    if ($tres) { $row = $tres->fetch_assoc(); $total_balance = floatval($row['total'] ?? 0); }
}

$list_query = 'SELECT id,name,phone,address,note,balance,created_at FROM customers' . $filter_sql . ' ORDER BY name';
if ($types) {
    $stmt = $conn->prepare($list_query);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $res = $stmt->get_result();
} else {
    $res = $conn->query($list_query);
}
?>

<style>
:root{
  --bg:#f6f8fb;
  --card:#ffffff;
  --muted:#6b7280;
  --accent:#0b63d6;
  --accent-2:#2563eb;
  --success:#16a34a;
  --danger:#ef4444;
  --soft:#f1f5f9;
  --text:#0f172a;
  --glass: rgba(255,255,255,0.6);
}
*{box-sizing:border-box}
body{font-family:Inter,system-ui,-apple-system,'Segoe UI',Roboto,Arial;background:linear-gradient(180deg,#f8fbff,#f6f8fb);color:var(--text);margin:0;padding:0}
.container{max-width:1200px;margin:36px auto;padding:20px}
.card{background:var(--card);border-radius:14px;padding:20px;box-shadow:0 12px 40px rgba(15,23,42,0.06);border:1px solid rgba(15,23,42,0.04)}
.header-row{display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:14px}
.title-group h2{margin:0;font-size:20px}
.controls{display:flex;gap:10px;align-items:center}
.btn{padding:10px 14px;border-radius:10px;text-decoration:none;background:var(--accent);color:#fff;font-weight:600;border:none;cursor:pointer;display:inline-flex;align-items:center;gap:8px}
.btn.ghost{background:transparent;border:1px solid #e6e9ee;color:var(--text)}
.btn.secondary{background:transparent;border:1px solid rgba(37,99,235,0.08);color:var(--accent-2)}
.btn.danger{background:var(--danger);color:#fff}
.btn.pill{padding:8px 12px;border-radius:999px;background:linear-gradient(90deg,#eef2ff,#f8fbff);border:1px solid #e6f0ff;color:var(--text);font-weight:700}
.search{display:flex;gap:8px;align-items:center}
.search input{padding:10px 12px;border-radius:10px;border:1px solid #e6e9ee;min-width:260px}
.kv{display:flex;flex-direction:column;align-items:flex-end}
.kv .label{font-size:13px;color:var(--muted)}
.kv .value{font-weight:800;font-size:18px;margin-top:6px}
.table-wrap{overflow:auto;margin-top:12px;border-radius:10px}
.table{width:100%;border-collapse:collapse;min-width:900px}
.table thead th{padding:14px;text-align:left;font-size:13px;color:var(--muted);border-bottom:1px solid #eef2f6}
.table td{padding:12px;border-bottom:1px solid #f3f4f6;vertical-align:middle}
.small-muted{color:var(--muted);font-size:13px}
.link{color:var(--accent-2);cursor:pointer;text-decoration:none}
.badge{display:inline-block;padding:6px 10px;border-radius:999px;background:var(--soft);color:var(--text);font-size:12px}
.balance-positive{color:var(--success);font-weight:700}
.balance-negative{color:var(--danger);font-weight:700}
.details-row{background:#fbfbfd;display:none}
.details-cell{padding:14px;color:var(--text);font-size:14px;border-bottom:1px solid #f3f4f6}
.actions a, .actions button{margin-left:8px;color:var(--text);text-decoration:none}
.empty-state{padding:24px;text-align:center;color:var(--muted)}
@media (max-width:880px){
  .search input{min-width:140px}
  .kv{align-items:flex-start}
  .table{min-width:700px}
}
.spinner{width:16px;height:16px;border-radius:50%;border:2px solid rgba(0,0,0,0.08);border-top-color:rgba(0,0,0,0.25);animation:spin 0.9s linear infinite;display:inline-block}
@keyframes spin{to{transform:rotate(360deg)}}
</style>

<div class="container">
  <div class="card">
    <div class="header-row">
      <div class="title-group">
        <h2>My Customers</h2>
        <?php if ($msg): ?><p style="color:green;margin:8px 0 0"><?php echo htmlspecialchars($msg) ?></p><?php endif; ?>
      </div>

      <div class="controls">
        <!-- Deactivated (trash) pill with count -->
        <a href="deactivate.php" class="btn pill" title="View deactivated customers">
          🗑️ Deactivated
          <span style="background:#fff;border-radius:999px;padding:4px 8px;margin-left:8px;font-weight:700;color:#0b63d6"><?php echo $inactive_count ?></span>
        </a>

        <a href="bakikhata.php?view=inactive" class="btn ghost" style="padding:8px 12px">View khata</a>

        <a href="add-customer.php" class="btn">+ Add Customer</a>
      </div>
    </div>

    <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:12px;flex-wrap:wrap">
      <form method="get" style="margin:0;display:flex;gap:8px;align-items:center" class="search">
        <input type="hidden" name="view" value="<?php echo htmlspecialchars($view) ?>">
        <input type="text" name="q" value="<?php echo htmlspecialchars($search) ?>" placeholder="Search name, phone or address">
        <button type="submit" class="btn secondary">Search</button>
        <a href="my-customer.php?view=<?php echo $view ?>" class="btn ghost">Clear</a>
      </form>

      <div style="display:flex;align-items:center;gap:12px">
        <div class="kv">
          <div class="label">My all total baki</div>
          <div class="value">৳ <?php echo number_format($total_balance,2) ?></div>
        </div>
      </div>
    </div>

    <div class="table-wrap">
      <table class="table" role="table">
        <thead>
          <tr>
            <th style="width:70px">ID</th>
            <th>Name</th>
            <th>Phone</th>
            <th>Address</th>
            <th>Note</th>
            <th style="text-align:right">Balance (৳)</th>
            <th>Joined</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
        <?php if ($res && $res->num_rows): ?>
          <?php while($c = $res->fetch_assoc()):
              $cid = (int)$c['id'];
              $cname = htmlspecialchars($c['name']);
              $cphone = htmlspecialchars($c['phone']);
              $cbalance_val = floatval($c['balance']);
              $cbalance = number_format($cbalance_val,2);
              $cjoined = htmlspecialchars($c['created_at']);
              $balance_class = $cbalance_val >= 0 ? 'balance-positive' : 'balance-negative';
          ?>
            <tr id="row-<?php echo $cid ?>">
              <td><?php echo $cid ?></td>
              <td><?php echo $cname ?></td>
              <td style="white-space:nowrap"><?php echo $cphone ?></td>
              <td style="max-width:240px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?php echo htmlspecialchars($c['address']) ?></td>
              <td style="max-width:180px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?php echo htmlspecialchars($c['note']) ?></td>
              <td style="text-align:right" class="<?php echo $balance_class ?>">৳ <?php echo $cbalance ?></td>
              <td style="white-space:nowrap"><?php echo $cjoined ?></td>
              <td style="white-space:nowrap">
                <button class="btn secondary" data-cid="<?php echo $cid ?>" data-action="view">View</button>
                <a href="add-customer.php?id=<?php echo $cid ?>" class="btn ghost" style="padding:8px 10px">Edit</a>

                <?php if ($view === 'active'): ?>
                  <button class="btn ghost" data-cid="<?php echo $cid ?>" data-action="deactivate">Deactivate</button>
                <?php else: ?>
                  <button class="btn secondary" data-cid="<?php echo $cid ?>" data-action="reactivate">Reactivate</button>
                  <button class="btn danger" data-cid="<?php echo $cid ?>" data-action="permanent-delete">Permanently Delete</button>
                <?php endif; ?>
              </td>
            </tr>

            <!-- details row -->
            <tr class="details-row" id="details-<?php echo $cid ?>">
              <td class="details-cell" colspan="8">
                <div style="display:flex;gap:18px;flex-wrap:wrap;align-items:flex-start">
                  <div style="min-width:220px">
                    <div style="font-weight:700"><?php echo $cname ?></div>
                    <div class="small-muted">Phone: <?php echo $cphone ?></div>
                    <div class="small-muted">Joined: <?php echo $cjoined ?></div>
                  </div>

                  <div style="flex:1;min-width:240px">
                    <div style="font-weight:600;margin-bottom:6px">Address</div>
                    <div style="color:#374151"><?php echo nl2br(htmlspecialchars($c['address'])) ?: '<span style="color:#9ca3af">— no address —</span>' ?></div>
                  </div>

                  <div style="flex:1;min-width:220px">
                    <div style="font-weight:600;margin-bottom:6px">Note</div>
                    <div style="color:#374151"><?php echo nl2br(htmlspecialchars($c['note'])) ?: '<span style="color:#9ca3af">— no note —</span>' ?></div>
                  </div>

                  <div style="min-width:180px;text-align:right">
                    <div style="font-weight:700">Balance</div>
                    <div style="font-size:18px;margin-top:6px" class="<?php echo $balance_class ?>">৳ <?php echo $cbalance ?></div>
                    <div style="margin-top:10px">
                      <a href="bakikhata.php?customer_id=<?php echo $cid ?>" class="btn ghost" style="margin-right:6px">Open Ledger</a>
                      <a href="add-customer.php?id=<?php echo $cid ?>" class="btn ghost">Edit</a>
                    </div>
                  </div>
                </div>

                <!-- server-side ledger preview -->
                <div style="margin-top:14px">
                  <h4 style="margin:0 0 8px 0">Recent Ledger (latest first)</h4>
                  <?php
                  $ledger_stmt = $conn->prepare('SELECT id, amount, type, note, created_at FROM bakhi_records WHERE customer_id = ? ORDER BY created_at DESC, id DESC LIMIT 100');
                  if ($ledger_stmt) {
                      $ledger_stmt->bind_param('i', $cid);
                      $ledger_stmt->execute();
                      $ld_res = $ledger_stmt->get_result();
                      $running = floatval($c['balance']);
                      if ($ld_res && $ld_res->num_rows):
                  ?>
                    <table class="table-sm" role="table" style="width:100%;margin-top:8px;border-collapse:collapse">
                      <thead>
                        <tr>
                          <th>ID</th>
                          <th>Type</th>
                          <th>Amount</th>
                          <th>Note</th>
                          <th>At</th>
                          <th style="text-align:right">Lenden</th>
                        </tr>
                      </thead>
                      <tbody>
                      <?php while ($lr = $ld_res->fetch_assoc()):
                          $l_signed = ($lr['type'] === 'dilam') ? floatval($lr['amount']) : -floatval($lr['amount']);
                          $balance_after = $running;
                          $running -= $l_signed;
                      ?>
                        <tr>
                          <td><?php echo (int)$lr['id'] ?></td>
                          <td><?php echo htmlspecialchars($lr['type']) ?></td>
                          <td><?php $sign = ($lr['type']==='dilam')?'+':'-'; echo $sign . ' ' . number_format(floatval($lr['amount']),2); ?></td>
                          <td><?php echo htmlspecialchars($lr['note']) ?></td>
                          <td><?php echo htmlspecialchars($lr['created_at']) ?></td>
                          <td style="text-align:right">৳ <?php echo number_format($balance_after,2) ?></td>
                        </tr>
                      <?php endwhile; ?>
                      </tbody>
                    </table>
                  <?php
                      else:
                          echo '<div class="small-muted">No ledger records.</div>';
                      endif;
                      $ledger_stmt->close();
                  } else {
                      echo '<div class="small-muted">Could not load ledger.</div>';
                  }
                  ?>
                </div>

              </td>
            </tr>

          <?php endwhile; ?>
        <?php else: ?>
          <tr><td colspan="8" class="empty-state">No customers found.</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function(){
  // Toggle details
  document.querySelectorAll('button[data-action="view"]').forEach(function(el){
    el.addEventListener('click', function(){
      var cid = this.getAttribute('data-cid');
      var details = document.getElementById('details-' + cid);
      if (!details) return;
      if (details.style.display === 'table-row' || details.style.display === 'block') { details.style.display = 'none'; }
      else { document.querySelectorAll('.details-row').forEach(function(r){ r.style.display = 'none'; }); details.style.display = 'table-row'; details.scrollIntoView({behavior:'smooth', block:'center'}); }
    });
  });

  // Generic AJAX action handler (keeps GET endpoints)
  function sendAction(btn, urlQuery, confirmMsg, successText) {
    btn.addEventListener('click', function(){
      var cid = this.getAttribute('data-cid');
      if (!cid) return;
      if (confirmMsg && !confirm(confirmMsg)) return;
      var originalHtml = btn.innerHTML;
      btn.disabled = true;
      btn.innerHTML = '<span class="spinner"></span>';

      fetch(window.location.pathname + urlQuery + encodeURIComponent(cid), { credentials:'same-origin', headers:{ 'X-Requested-With':'XMLHttpRequest' } })
      .then(function(resp){ const ct = resp.headers.get('content-type') || ''; if (ct.indexOf('application/json') !== -1) return resp.json(); return resp.text().then(function(t){ try { return JSON.parse(t); } catch(e){ return { success:false, error: t }; } }); })
      .then(function(json){
        if (json && json.success) {
          var row = document.getElementById('row-' + cid);
          var details = document.getElementById('details-' + cid);
          if (row) row.parentNode.removeChild(row);
          if (details) details.parentNode.removeChild(details);
          if (successText) alert(successText);
          // update Deactivated count pill quickly (best-effort)
          var pill = document.querySelector('.btn.pill span');
          if (pill) {
            var n = parseInt(pill.textContent || '0',10);
            if (urlQuery.indexOf('?delete=') === 0) { pill.textContent = Math.max(0, n+1); } // one more deactivated
            if (urlQuery.indexOf('?reactivate=') === 0) { pill.textContent = Math.max(0, n-1); } // one less deactivated
          }
        } else {
          alert((json && json.error) ? json.error : 'Operation failed');
          btn.disabled = false; btn.innerHTML = originalHtml;
        }
      }).catch(function(err){ console.error(err); alert('Network error'); btn.disabled = false; btn.innerHTML = originalHtml; });
    });
  }

  document.querySelectorAll('button[data-action="deactivate"]').forEach(function(btn){ sendAction(btn, '?delete=', 'Deactivate this customer? They will be hidden from active list.', 'Customer deactivated.'); });
  document.querySelectorAll('button[data-action="reactivate"]').forEach(function(btn){ sendAction(btn, '?reactivate=', 'Reactivate this customer?', 'Customer reactivated.'); });
  document.querySelectorAll('button[data-action="permanent-delete"]').forEach(function(btn){ sendAction(btn, '?permanent_delete=', 'Permanently delete? This will remove the customer and all their ledger records. This cannot be undone.', 'Customer permanently deleted.'); });
});
</script>

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