<?php
// deactivate.php
// Shows list of deactivated customers (active = 0).
// Allows Reactivate (enable) and Permanently Delete (destructive).
// Requires: db.php (mysqli connection)
// IMPORTANT: ensure customers table has `active` column:
// ALTER TABLE customers ADD COLUMN active TINYINT(1) NOT NULL DEFAULT 1;

session_start();
require 'db.php';

// simple auth check placeholder (optional)
// if (empty($_SESSION['user_id'])) { header('Location: login.php'); exit; }

// generate CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
}
$CSRF = $_SESSION['csrf_token'];

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

// handle POST actions (reactivate, permanent_delete)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');

    // read JSON or form-encoded POST
    $input = json_decode(file_get_contents('php://input'), true);
    if (!is_array($input)) $input = $_POST;

    $action = $input['action'] ?? null;
    $id = isset($input['id']) ? intval($input['id']) : 0;
    $token = $input['csrf'] ?? '';

    if ($token !== $CSRF) {
        http_response_code(403);
        echo json_encode(['success' => false, 'error' => 'Invalid CSRF token']);
        exit;
    }

    if (!in_array($action, ['reactivate','permanent_delete'])) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Invalid action']);
        exit;
    }

    if ($id <= 0) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Invalid id']);
        exit;
    }

    // Reactivate (soft enable)
    if ($action === 'reactivate') {
        $stmt = $conn->prepare('UPDATE customers SET active = 1 WHERE id = ?');
        if (!$stmt) {
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'DB prepare failed: '.$conn->error]);
            exit;
        }
        $stmt->bind_param('i', $id);
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'id' => $id]);
            $stmt->close();
            exit;
        } else {
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'Update failed: '.$stmt->error]);
            $stmt->close();
            exit;
        }
    }

    // Permanent delete (destructive) — only allow for inactive customers
    if ($action === 'permanent_delete') {
        // check exists and inactive
        $chk = $conn->prepare('SELECT active FROM customers WHERE id = ?');
        if (!$chk) {
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'DB prepare failed: '.$conn->error]);
            exit;
        }
        $chk->bind_param('i', $id);
        $chk->execute();
        $cres = $chk->get_result()->fetch_assoc();
        $chk->close();
        if (!$cres) {
            http_response_code(404);
            echo json_encode(['success' => false, 'error' => 'Customer not found']);
            exit;
        }
        if (intval($cres['active']) === 1) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'Customer is active. Deactivate first.']);
            exit;
        }

        // transaction: delete ledger then customer
        $conn->begin_transaction();
        try {
            $d1 = $conn->prepare('DELETE FROM bakhi_records WHERE customer_id = ?');
            if (!$d1) throw new Exception('Prepare ledger-delete failed: '.$conn->error);
            $d1->bind_param('i', $id);
            $d1->execute();
            $ledgerDeleted = $d1->affected_rows;
            $d1->close();

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

            $conn->commit();
            echo json_encode(['success' => true, 'ledger_deleted' => $ledgerDeleted, 'customer_deleted' => $custDeleted]);
            exit;
        } catch (Exception $e) {
            $conn->rollback();
            $err = $e->getMessage();
            // check FK typical errno
            $hint = ($conn->errno === 1451) ? 'Foreign key prevents delete.' : '';
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'Delete failed: '.$err, 'hint'=>$hint, 'errno'=>$conn->errno]);
            exit;
        }
    }

    // default fallback
    http_response_code(400);
    echo json_encode(['success'=>false,'error'=>'Unknown request']);
    exit;
}

// If GET: render page showing deactivated customers
// Fetch inactive customers
$res = $conn->query('SELECT id,name,phone,address,note,balance,created_at FROM customers WHERE active = 0 ORDER BY name');

?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Deactivated Customers</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
:root{--bg:#f6f8fb;--card:#fff;--muted:#6b7280;--accent:#0b63d6;--danger:#ef4444;--text:#0f172a}
body{font-family:Inter,system-ui,-apple-system,Segoe UI,Roboto,Arial;background:var(--bg);color:var(--text);margin:0;padding:20px}
.container{max-width:1100px;margin:0 auto}
.card{background:var(--card);padding:18px;border-radius:12px;box-shadow:0 8px 24px rgba(15,23,42,0.06)}
.table{width:100%;border-collapse:collapse;margin-top:12px}
.table th{background:transparent;text-align:left;padding:10px;color:var(--muted);font-weight:600;border-bottom:1px solid #eef2f6}
.table td{padding:10px;border-bottom:1px solid #f3f4f6;vertical-align:middle}
.btn{padding:8px 12px;border-radius:8px;border:none;cursor:pointer}
.btn.ghost{background:transparent;border:1px solid #e6e9ee;color:var(--text)}
.btn.primary{background:var(--accent);color:#fff}
.btn.danger{background:var(--danger);color:#fff}
.small{font-size:13px;color:var(--muted)}
.header{display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap}
.spinner{width:14px;height:14px;border-radius:50%;border:2px solid rgba(0,0,0,0.08);border-top-color:rgba(0,0,0,0.25);animation:spin .9s linear infinite;display:inline-block;vertical-align:middle}
@keyframes spin{to{transform:rotate(360deg)}}
.empty{padding:24px;text-align:center;color:var(--muted)}
</style>
</head>
<body>
<div class="container">
  <div class="card">
    <div class="header">
      <div>
        <h2 style="margin:0">Deactivated Customers</h2>
        <div class="small" style="margin-top:6px">List of customers with <code>active = 0</code>. You can reactivate or permanently delete them.</div>
      </div>
      <div style="display:flex;gap:8px;align-items:center">
        <a href="my-customer.php" class="btn ghost">Back to Active</a>
        <button id="refreshBtn" class="btn ghost">Refresh</button>
      </div>
    </div>

    <?php if ($res && $res->num_rows): ?>
    <table class="table" role="table">
      <thead>
        <tr>
          <th style="width:60px">ID</th>
          <th>Name</th>
          <th>Phone</th>
          <th>Address</th>
          <th style="text-align:right">Balance (৳)</th>
          <th>Joined</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
      <?php while ($c = $res->fetch_assoc()): 
          $cid = (int)$c['id'];
      ?>
        <tr id="row-<?php echo $cid ?>">
          <td><?php echo $cid ?></td>
          <td><?php echo htmlspecialchars($c['name']) ?></td>
          <td><?php echo htmlspecialchars($c['phone']) ?></td>
          <td style="max-width:240px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?php echo htmlspecialchars($c['address']) ?></td>
          <td style="text-align:right"><?php echo number_format(floatval($c['balance']),2) ?></td>
          <td><?php echo htmlspecialchars($c['created_at']) ?></td>
          <td style="white-space:nowrap">
            <button class="btn primary" data-action="reactivate" data-id="<?php echo $cid ?>">Reactivate</button>
            <button class="btn danger" data-action="permanent_delete" data-id="<?php echo $cid ?>">Permanently Delete</button>
          </td>
        </tr>
      <?php endwhile; ?>
      </tbody>
    </table>
    <?php else: ?>
      <div class="empty">No deactivated customers found.</div>
    <?php endif; ?>
  </div>
</div>

<script>
// CSRF token from PHP session
const CSRF = '<?php echo $CSRF ?>';

// helper to POST JSON
function postJSON(url, payload){
  return fetch(url, {
    method: 'POST',
    credentials: 'same-origin',
    headers: {'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest'},
    body: JSON.stringify(payload)
  }).then(r => r.json().catch(()=>({success:false,error:'Invalid JSON response'})));
}

function attachHandlers(){
  document.querySelectorAll('button[data-action="reactivate"]').forEach(btn => {
    btn.addEventListener('click', function(){
      const id = parseInt(this.dataset.id,10);
      if (!id) return;
      if (!confirm('Reactivate this customer?')) return;
      const orig = this.innerHTML;
      this.disabled = true;
      this.innerHTML = '<span class="spinner"></span>';
      postJSON(window.location.pathname, { action:'reactivate', id:id, csrf:CSRF })
        .then(json => {
          if (json && json.success) {
            const row = document.getElementById('row-' + id);
            if (row) row.remove();
            alert('Customer reactivated.');
          } else {
            alert('Reactivate failed: ' + (json && json.error ? json.error : 'Unknown'));
            this.disabled = false;
            this.innerHTML = orig;
          }
        }).catch(err => { console.error(err); alert('Network error'); this.disabled=false; this.innerHTML=orig; });
    });
  });

  document.querySelectorAll('button[data-action="permanent_delete"]').forEach(btn => {
    btn.addEventListener('click', function(){
      const id = parseInt(this.dataset.id,10);
      if (!id) return;
      if (!confirm('Permanently delete this customer and ALL their ledger records? This cannot be undone.')) return;
      const orig = this.innerHTML;
      this.disabled = true;
      this.innerHTML = '<span class="spinner"></span>';
      postJSON(window.location.pathname, { action:'permanent_delete', id:id, csrf:CSRF })
        .then(json => {
          if (json && json.success) {
            const row = document.getElementById('row-' + id);
            if (row) row.remove();
            alert('Customer permanently deleted.');
          } else {
            const err = (json && json.error) ? json.error : 'Unknown';
            alert('Delete failed: ' + err + (json && json.hint ? '\\nHint: ' + json.hint : ''));
            this.disabled = false;
            this.innerHTML = orig;
          }
        }).catch(err => { console.error(err); alert('Network error'); this.disabled=false; this.innerHTML=orig; });
    });
  });

  // refresh
  const refreshBtn = document.getElementById('refreshBtn');
  if (refreshBtn) refreshBtn.addEventListener('click', ()=> location.reload());
}

document.addEventListener('DOMContentLoaded', attachHandlers);
</script>
</body>
</html>
