<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>POS Resto - Dashboard Admin</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #f0f2f5; color: #333; }

/* ===== LOGIN ===== */
#loginPage { display: flex; align-items: center; justify-content: center; min-height: 100vh; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.login-box { background: #fff; padding: 40px; border-radius: 12px; box-shadow: 0 10px 40px rgba(0,0,0,0.2); width: 100%; max-width: 400px; }
.login-box h1 { text-align: center; margin-bottom: 8px; font-size: 24px; }
.login-box p { text-align: center; color: #888; margin-bottom: 24px; font-size: 14px; }
.login-box input { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 15px; margin-bottom: 12px; }
.login-box button { width: 100%; padding: 12px; background: #667eea; color: #fff; border: none; border-radius: 8px; font-size: 16px; cursor: pointer; font-weight: 600; }
.login-box button:hover { background: #5a6fd6; }
.login-box button:disabled { background: #aaa; cursor: not-allowed; }
.login-error { color: #e74c3c; font-size: 13px; text-align: center; margin-bottom: 12px; display: none; }

/* ===== DASHBOARD ===== */
#dashboardPage { display: none; }
.nav { background: #fff; border-bottom: 1px solid #e0e0e0; padding: 0 24px; display: flex; align-items: center; height: 60px; }
.nav h2 { font-size: 18px; flex: 1; }
.nav .user-info { font-size: 14px; color: #888; margin-right: 16px; }
.nav button { padding: 8px 16px; background: #e74c3c; color: #fff; border: none; border-radius: 6px; cursor: pointer; font-size: 14px; }
.nav button:hover { background: #c0392b; }

.tabs { display: flex; background: #fff; border-bottom: 2px solid #e0e0e0; padding: 0 24px; }
.tabs button { padding: 12px 24px; background: none; border: none; border-bottom: 2px solid transparent; margin-bottom: -2px; cursor: pointer; font-size: 15px; color: #888; font-weight: 500; }
.tabs button.active { color: #667eea; border-bottom-color: #667eea; }

.tab-content { display: none; padding: 24px; max-width: 1200px; margin: 0 auto; }
.tab-content.active { display: block; }

/* Summary cards */
.summary-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 24px; }
.summary-card { background: #fff; padding: 20px; border-radius: 10px; box-shadow: 0 1px 4px rgba(0,0,0,0.08); }
.summary-card h3 { font-size: 13px; color: #888; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 8px; }
.summary-card .value { font-size: 28px; font-weight: 700; color: #333; }

/* Table */
.table-wrapper { background: #fff; border-radius: 10px; box-shadow: 0 1px 4px rgba(0,0,0,0.08); overflow-x: auto; }
table { width: 100%; border-collapse: collapse; font-size: 14px; }
th, td { padding: 12px 16px; text-align: left; border-bottom: 1px solid #f0f0f0; }
th { background: #fafafa; font-weight: 600; font-size: 13px; color: #666; text-transform: uppercase; letter-spacing: 0.3px; }
tr:hover { background: #f8f9ff; }
img.product-img { width: 50px; height: 50px; object-fit: cover; border-radius: 6px; background: #f0f0f0; }
img.product-img[src=""] { display: none; }

/* Buttons */
.btn { padding: 8px 16px; border: none; border-radius: 6px; cursor: pointer; font-size: 13px; font-weight: 500; }
.btn-primary { background: #667eea; color: #fff; }
.btn-primary:hover { background: #5a6fd6; }
.btn-danger { background: #e74c3c; color: #fff; }
.btn-danger:hover { background: #c0392b; }
.btn-sm { padding: 5px 10px; font-size: 12px; }
.btn-success { background: #27ae60; color: #fff; }
.btn-success:hover { background: #219a52; }
.btn-warning { background: #f39c12; color: #fff; }

/* Form modal */
.modal-overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 100; align-items: center; justify-content: center; }
.modal-overlay.active { display: flex; }
.modal { background: #fff; border-radius: 12px; padding: 32px; width: 100%; max-width: 500px; max-height: 90vh; overflow-y: auto; box-shadow: 0 20px 60px rgba(0,0,0,0.3); }
.modal h2 { margin-bottom: 20px; font-size: 20px; }
.form-group { margin-bottom: 16px; }
.form-group label { display: block; font-size: 13px; font-weight: 600; color: #555; margin-bottom: 6px; }
.form-group input, .form-group select, .form-group textarea { width: 100%; padding: 10px 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 14px; font-family: inherit; }
.form-group textarea { resize: vertical; min-height: 60px; }
.form-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 20px; }
.img-preview { width: 80px; height: 80px; object-fit: cover; border-radius: 8px; border: 2px solid #ddd; margin-top: 8px; }
.badge { display: inline-block; padding: 3px 10px; border-radius: 20px; font-size: 12px; font-weight: 600; }
.badge-active { background: #d4edda; color: #155724; }
.badge-inactive { background: #f8d7da; color: #721c24; }

/* Toast */
.toast { position: fixed; top: 20px; right: 20px; padding: 14px 24px; border-radius: 8px; color: #fff; font-size: 14px; z-index: 999; display: none; box-shadow: 0 4px 16px rgba(0,0,0,0.2); }
.toast.success { background: #27ae60; }
.toast.error { background: #e74c3c; }

/* Empty state */
.empty { text-align: center; padding: 40px; color: #aaa; font-size: 15px; }

/* Toolbar */
.toolbar { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; flex-wrap: wrap; gap: 8px; }
.toolbar input[type="text"] { padding: 9px 14px; border: 1px solid #ddd; border-radius: 8px; font-size: 14px; width: 250px; }
.toolbar select { padding: 9px 14px; border: 1px solid #ddd; border-radius: 8px; font-size: 14px; }

/* Responsive */
@media (max-width: 768px) {
  .summary-row { grid-template-columns: 1fr 1fr; }
  .toolbar { flex-direction: column; align-items: stretch; }
  .toolbar input[type="text"] { width: 100%; }
  .tabs { overflow-x: auto; }
  .tabs button { white-space: nowrap; }
}
</style>
</head>
<body>

<!-- Toast -->
<div id="toast" class="toast"></div>

<!-- ===== LOGIN ===== -->
<div id="loginPage">
  <div class="login-box">
    <h1>POS Resto</h1>
    <p>Dashboard Admin</p>
    <div id="loginError" class="login-error"></div>
    <input type="email" id="loginEmail" placeholder="Email" value="admin@posresto.com">
    <input type="password" id="loginPassword" placeholder="Password" value="admin123">
    <button id="loginBtn" onclick="doLogin()">Login</button>
  </div>
</div>

<!-- ===== DASHBOARD ===== -->
<div id="dashboardPage">
  <div class="nav">
    <h2>POS Resto Admin</h2>
    <span class="user-info" id="userName"></span>
    <button onclick="doLogout()">Logout</button>
  </div>

  <div class="tabs">
    <button class="active" onclick="switchTab('products')">Produk</button>
    <button onclick="switchTab('categories')">Kategori</button>
    <button onclick="switchTab('orders')">Orders</button>
    <button onclick="switchTab('payment')">Pembayaran</button>
    <button onclick="switchTab('outlets')">Outlet</button>
    <button onclick="switchTab('users')">Kasir</button>
  </div>

  <!-- TAB: Products -->
  <div id="tab-products" class="tab-content active">
    <div class="toolbar">
      <div>
        <input type="text" id="searchProduct" placeholder="Cari produk..." oninput="renderProducts()">
        <select id="filterCategory" onchange="renderProducts()"><option value="">Semua Kategori</option></select>
      </div>
      <button class="btn btn-primary" onclick="openProductModal()">+ Tambah Produk</button>
    </div>
    <div class="table-wrapper">
      <table>
        <thead><tr><th>Foto</th><th>Nama</th><th>Kategori</th><th>Harga</th><th>Stok</th><th>Status</th><th>Fav</th><th>Aksi</th></tr></thead>
        <tbody id="productsBody"></tbody>
      </table>
    </div>
  </div>

  <!-- TAB: Categories -->
  <div id="tab-categories" class="tab-content">
    <div class="toolbar">
      <div></div>
      <button class="btn btn-primary" onclick="openCategoryModal()">+ Tambah Kategori</button>
    </div>
    <div class="table-wrapper">
      <table>
        <thead><tr><th>ID</th><th>Nama</th><th>Deskripsi</th><th>Jumlah Produk</th><th>Aksi</th></tr></thead>
        <tbody id="categoriesBody"></tbody>
      </table>
    </div>
  </div>

  <!-- TAB: Orders -->
  <div id="tab-orders" class="tab-content">
    <div class="toolbar">
      <input type="date" id="orderDate" onchange="loadOrders()">
      <div></div>
    </div>
    <div class="summary-row" id="orderSummary"></div>
    <h3 style="margin:20px 0 10px;font-size:15px;color:#555">Pemasukan per Outlet</h3>
    <div class="summary-row" id="outletSummary"></div>
    <div class="table-wrapper">
      <table>
        <thead><tr><th>No</th><th>Waktu</th><th>ORD#</th><th>Tipe</th><th>Meja</th><th>Kasir</th><th>Items</th><th>Total</th><th>Bayar</th><th>Status</th><th>Aksi</th></tr></thead>
        <tbody id="ordersBody"></tbody>
      </table>
    </div>
  </div>

  <!-- TAB: Pembayaran -->
  <div id="tab-payment" class="tab-content">
    <div class="toolbar">
      <div></div>
      <button class="btn btn-primary" onclick="openPaymentModal()">+ Tambah Metode</button>
    </div>
    <div class="table-wrapper">
      <table>
        <thead><tr><th>ID</th><th>Nama</th><th>Tipe</th><th>Bank</th><th>Atas Nama</th><th>No. Rekening</th><th>Status</th><th>Aksi</th></tr></thead>
        <tbody id="paymentBody"></tbody>
      </table>
    </div>
  </div>

  <!-- TAB: Outlets -->
  <div id="tab-outlets" class="tab-content">
    <div class="toolbar">
      <div></div>
      <button class="btn btn-primary" onclick="openOutletModal()">+ Tambah Outlet</button>
    </div>
    <div class="table-wrapper">
      <table>
        <thead><tr><th>ID</th><th>Nama</th><th>Alamat</th><th>Status</th><th>Aksi</th></tr></thead>
        <tbody id="outletsBody"></tbody>
      </table>
    </div>
  </div>

  <!-- TAB: Kasir -->
  <div id="tab-users" class="tab-content">
    <div class="toolbar">
      <div></div>
      <button class="btn btn-primary" onclick="openUserModal()">+ Tambah Kasir</button>
    </div>
    <div class="table-wrapper">
      <table>
        <thead><tr><th>ID</th><th>Nama</th><th>Email</th><th>Role</th><th>Outlet</th><th>Aksi</th></tr></thead>
        <tbody id="usersBody"></tbody>
      </table>
    </div>
  </div>
</div>

<!-- Modal: Product -->
<div id="productModal" class="modal-overlay">
  <div class="modal">
    <h2 id="productModalTitle">Tambah Produk</h2>
    <input type="hidden" id="pId">
    <div class="form-group"><label>Nama Produk *</label><input type="text" id="pName"></div>
    <div class="form-group"><label>Kategori</label><select id="pCategory"><option value="">Tanpa Kategori</option></select></div>
    <div class="form-group"><label>Deskripsi</label><textarea id="pDesc"></textarea></div>
    <div class="form-group"><label>Harga (Rp) *</label><input type="text" id="pPrice" placeholder="25000"></div>
    <div class="form-group"><label>Stok</label><input type="number" id="pStock" value="0"></div>
    <div class="form-group"><label>Foto</label><input type="file" id="pImage" accept="image/*" onchange="previewImage(this)"><br><img id="pImagePreview" class="img-preview" style="display:none"><input type="hidden" id="pImageUrl"></div>
    <div class="form-group"><label>Status</label><select id="pStatus"><option value="1">Aktif</option><option value="0">Nonaktif</option></select></div>
    <div class="form-group"><label>Favorit</label><select id="pFav"><option value="0">Tidak</option><option value="1">Ya</option></select></div>
    <div class="form-actions">
      <button class="btn" onclick="closeProductModal()" style="background:#eee">Batal</button>
      <button class="btn btn-primary" id="saveProductBtn" onclick="saveProduct()">Simpan</button>
    </div>
  </div>
</div>

<!-- Modal: Category -->
<div id="categoryModal" class="modal-overlay">
  <div class="modal">
    <h2 id="categoryModalTitle">Tambah Kategori</h2>
    <input type="hidden" id="cId">
    <div class="form-group"><label>Nama Kategori *</label><input type="text" id="cName"></div>
    <div class="form-group"><label>Deskripsi</label><textarea id="cDesc"></textarea></div>
    <div class="form-actions">
      <button class="btn" onclick="closeCategoryModal()" style="background:#eee">Batal</button>
      <button class="btn btn-primary" onclick="saveCategory()">Simpan</button>
    </div>
  </div>
</div>

<!-- Modal: Payment Method -->
<div id="paymentModal" class="modal-overlay">
  <div class="modal">
    <h2 id="paymentModalTitle">Tambah Metode Pembayaran</h2>
    <input type="hidden" id="pmId">
    <div class="form-group"><label>Nama Metode *</label><input type="text" id="pmName" placeholder="QRIS / Transfer BCA / EDC"></div>
    <div class="form-group"><label>Tipe</label><select id="pmType">
      <option value="cash">Cash</option>
      <option value="qris">QRIS</option>
      <option value="edc">EDC (Kartu)</option>
      <option value="transfer">Transfer Bank</option>
    </select></div>
    <div class="form-group"><label>Nama Bank</label><input type="text" id="pmBank" placeholder="BCA / BRI"></div>
    <div class="form-group"><label>Atas Nama</label><input type="text" id="pmAccountName" placeholder="Nama pemilik rekening"></div>
    <div class="form-group"><label>No. Rekening</label><input type="text" id="pmAccountNumber" placeholder="1234567890"></div>
    <div class="form-group"><label>Status</label><select id="pmActive"><option value="1">Aktif</option><option value="0">Nonaktif</option></select></div>
    <div class="form-actions">
      <button class="btn" onclick="closePaymentModal()" style="background:#eee">Batal</button>
      <button class="btn btn-primary" onclick="savePaymentMethod()">Simpan</button>
    </div>
  </div>
</div>

<!-- Modal: Outlet -->
<div id="outletModal" class="modal-overlay">
  <div class="modal">
    <h2 id="outletModalTitle">Tambah Outlet</h2>
    <input type="hidden" id="oId">
    <div class="form-group"><label>Nama Outlet *</label><input type="text" id="oName" placeholder="Outlet 1"></div>
    <div class="form-group"><label>Alamat</label><input type="text" id="oAddress"></div>
    <div class="form-group"><label>Status</label><select id="oActive"><option value="1">Aktif</option><option value="0">Nonaktif</option></select></div>
    <div class="form-actions">
      <button class="btn" onclick="closeOutletModal()" style="background:#eee">Batal</button>
      <button class="btn btn-primary" onclick="saveOutlet()">Simpan</button>
    </div>
  </div>
</div>

<!-- Modal: User/Kasir -->
<div id="userModal" class="modal-overlay">
  <div class="modal">
    <h2 id="userModalTitle">Tambah Kasir</h2>
    <input type="hidden" id="uId">
    <div class="form-group"><label>Nama *</label><input type="text" id="uName" placeholder="Kasir 1"></div>
    <div class="form-group"><label>Email *</label><input type="email" id="uEmail" placeholder="kasir1@outlet.com"></div>
    <div class="form-group"><label>Password *</label><input type="password" id="uPassword" placeholder="min 6 karakter"></div>
    <div class="form-group"><label>Role</label><select id="uRole"><option value="kasir">Kasir</option><option value="admin">Admin</option></select></div>
    <div class="form-group"><label>Outlet</label><select id="uOutlet"><option value="">Tanpa Outlet (Pusat)</option></select></div>
    <div class="form-actions">
      <button class="btn" onclick="closeUserModal()" style="background:#eee">Batal</button>
      <button class="btn btn-primary" onclick="saveUser()">Simpan</button>
    </div>
  </div>
</div>

<script>
const BASE = window.location.pathname.replace(/\/[^/]*$/, '').replace(/\/dashboard\.php$/, '') || '.';

let authToken = localStorage.getItem('pos_token') || '';
let userData = JSON.parse(localStorage.getItem('pos_user') || 'null');
let allProducts = [];
let allCategories = [];
let allPaymentMethods = [];
let allOutlets = [];
let allUsers = [];

// ===== INIT =====
window.addEventListener('DOMContentLoaded', () => {
  if (authToken && userData) {
    showDashboard();
  } else {
    showLogin();
  }
});

// ===== AUTH =====
async function doLogin() {
  const email = document.getElementById('loginEmail').value;
  const pass = document.getElementById('loginPassword').value;
  const errEl = document.getElementById('loginError');
  const btn = document.getElementById('loginBtn');
  errEl.style.display = 'none';
  btn.disabled = true; btn.textContent = 'Memproses...';
  try {
    const res = await fetch(BASE + '/api-login.php', {
      method: 'POST', headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({email, password: pass})
    });
    const data = await res.json();
    if (data.status === 'success') {
      authToken = data.token;
      userData = data.user;
      localStorage.setItem('pos_token', authToken);
      localStorage.setItem('pos_user', JSON.stringify(userData));
      showDashboard();
    } else {
      errEl.textContent = data.message;
      errEl.style.display = 'block';
    }
  } catch(e) {
    errEl.textContent = 'Gagal konek ke server. Pastikan XAMPP/Laragon sudah jalan.';
    errEl.style.display = 'block';
  }
  btn.disabled = false; btn.textContent = 'Login';
}

function doLogout() {
  authToken = ''; userData = null;
  localStorage.removeItem('pos_token'); localStorage.removeItem('pos_user');
  showLogin();
}

function showLogin() { document.getElementById('loginPage').style.display = 'flex'; document.getElementById('dashboardPage').style.display = 'none'; }
function showDashboard() {
  document.getElementById('loginPage').style.display = 'none';
  document.getElementById('dashboardPage').style.display = 'block';
  document.getElementById('userName').textContent = userData?.name || 'Admin';
  const now = new Date();
  document.getElementById('orderDate').value = now.getFullYear() + '-' + String(now.getMonth()+1).padStart(2,'0') + '-' + String(now.getDate()).padStart(2,'0');
  loadCategories(); loadProducts(); loadOrders(); loadPaymentMethods(); loadOutlets(); loadUsers();
}

// ===== API HELPER =====
async function api(url, opts = {}) {
  const headers = {'Authorization': 'Bearer ' + authToken, 'Accept': 'application/json', ...opts.headers};
  if (opts.body && typeof opts.body === 'string') headers['Content-Type'] = 'application/json';
  const res = await fetch(BASE + '/' + url, {...opts, headers});
  return res.json();
}

// ===== TABS =====
function switchTab(name) {
  document.querySelectorAll('.tabs button').forEach(b => b.classList.remove('active'));
  document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
  event.target.classList.add('active');
  document.getElementById('tab-' + name).classList.add('active');
  if (name === 'orders') loadOrders();
  if (name === 'outlets') loadOutlets();
  if (name === 'users') loadUsers();
}

// ===== TOAST =====
function toast(msg, type = 'success') {
  const el = document.getElementById('toast');
  el.textContent = msg; el.className = 'toast ' + type; el.style.display = 'block';
  setTimeout(() => el.style.display = 'none', 3000);
}

// ===== CATEGORIES =====
async function loadCategories() {
  const data = await api('api-categories.php');
  allCategories = data.data || [];
  renderCategoryOptions(); renderCategories();
}

function renderCategoryOptions() {
  let html = '<option value="">Semua Kategori</option><option value="">Tanpa Kategori</option>';
  allCategories.forEach(c => html += '<option value="' + c.id + '">' + esc(c.name) + '</option>');
  document.getElementById('filterCategory').innerHTML = html;
  document.getElementById('pCategory').innerHTML = '<option value="">Tanpa Kategori</option>' + allCategories.map(c => '<option value="' + c.id + '">' + esc(c.name) + '</option>').join('');
}

function renderCategories() {
  const tbody = document.getElementById('categoriesBody');
  if (!allCategories.length) { tbody.innerHTML = '<tr><td colspan="5" class="empty">Belum ada kategori</td></tr>'; return; }
  tbody.innerHTML = allCategories.map(c => {
    const pCount = allProducts.filter(p => p.category_id == c.id).length;
    return '<tr><td>' + c.id + '</td><td>' + esc(c.name) + '</td><td>' + esc(c.description || '-') + '</td><td>' + pCount + '</td><td><button class="btn btn-sm btn-warning" onclick="editCategory(' + c.id + ')">Edit</button> <button class="btn btn-sm btn-danger" onclick="deleteCategory(' + c.id + ')">Hapus</button></td></tr>';
  }).join('');
}

function openCategoryModal() { document.getElementById('cId').value = ''; document.getElementById('cName').value = ''; document.getElementById('cDesc').value = ''; document.getElementById('categoryModalTitle').textContent = 'Tambah Kategori'; document.getElementById('categoryModal').classList.add('active'); }
function closeCategoryModal() { document.getElementById('categoryModal').classList.remove('active'); }

async function editCategory(id) {
  const c = allCategories.find(x => x.id == id); if (!c) return;
  document.getElementById('cId').value = c.id; document.getElementById('cName').value = c.name; document.getElementById('cDesc').value = c.description || '';
  document.getElementById('categoryModalTitle').textContent = 'Edit Kategori';
  document.getElementById('categoryModal').classList.add('active');
}

async function saveCategory() {
  const id = document.getElementById('cId').value;
  const name = document.getElementById('cName').value.trim();
  if (!name) { toast('Nama kategori wajib diisi', 'error'); return; }
  const body = {id: id || undefined, name, description: document.getElementById('cDesc').value.trim()};
  const method = id ? 'PUT' : 'POST';
  const data = await api('api-categories.php', {method, body: JSON.stringify(body)});
  if (data.status === 'success') { toast(id ? 'Kategori diupdate' : 'Kategori ditambah'); closeCategoryModal(); loadCategories(); } else { toast(data.message || 'Gagal', 'error'); }
}

async function deleteCategory(id) {
  if (!confirm('Hapus kategori ini? (tidak bisa jika masih ada produk)')) return;
  const data = await api('api-categories.php', {method: 'DELETE', body: JSON.stringify({id})});
  if (data.status === 'success') { toast('Kategori dihapus'); loadCategories(); } else { toast(data.message || 'Gagal hapus', 'error'); }
}

// ===== PRODUCTS =====
async function loadProducts() {
  const data = await api('api-products.php');
  allProducts = data.data || [];
  renderProducts();
}

function renderProducts() {
  const search = (document.getElementById('searchProduct').value || '').toLowerCase();
  const catFilter = document.getElementById('filterCategory').value;
  let filtered = allProducts;
  if (search) filtered = filtered.filter(p => p.name.toLowerCase().includes(search));
  if (catFilter) filtered = filtered.filter(p => p.category_id == catFilter);
  const tbody = document.getElementById('productsBody');
  if (!filtered.length) { tbody.innerHTML = '<tr><td colspan="8" class="empty">Tidak ada produk</td></tr>'; return; }
  tbody.innerHTML = filtered.map(p => '<tr>' +
    '<td><img class="product-img" src="' + esc(p.image || '') + '" alt=""></td>' +
    '<td><strong>' + esc(p.name) + '</strong><br><small style="color:#888">' + esc(p.description || '').substring(0,50) + '</small></td>' +
    '<td>' + esc(p.category?.name || '-') + '</td>' +
    '<td>Rp ' + Number(p.price).toLocaleString('id-ID') + '</td>' +
    '<td>' + p.stock + '</td>' +
    '<td><span class="badge ' + (p.status == 1 ? 'badge-active' : 'badge-inactive') + '">' + (p.status == 1 ? 'Aktif' : 'Nonaktif') + '</span></td>' +
    '<td>' + (p.is_favorite == 1 ? '⭐' : '-') + '</td>' +
    '<td><button class="btn btn-sm btn-primary" onclick="editProduct(' + p.id + ')">Edit</button> <button class="btn btn-sm btn-danger" onclick="deleteProduct(' + p.id + ')">Hapus</button></td>' +
    '</tr>').join('');
}

function openProductModal() {
  ['pId','pName','pDesc','pPrice','pImageUrl'].forEach(id => document.getElementById(id).value = '');
  document.getElementById('pStock').value = '0';
  document.getElementById('pStatus').value = '1'; document.getElementById('pFav').value = '0';
  document.getElementById('pImage').value = '';
  document.getElementById('pImagePreview').style.display = 'none';
  document.getElementById('productModalTitle').textContent = 'Tambah Produk';
  document.getElementById('productModal').classList.add('active');
}
function closeProductModal() { document.getElementById('productModal').classList.remove('active'); }

function previewImage(input) {
  const file = input.files[0]; if (!file) return;
  const reader = new FileReader();
  reader.onload = e => { document.getElementById('pImagePreview').src = e.target.result; document.getElementById('pImagePreview').style.display = 'block'; };
  reader.readAsDataURL(file);
}

async function editProduct(id) {
  const p = allProducts.find(x => x.id == id); if (!p) return;
  document.getElementById('pId').value = p.id;
  document.getElementById('pName').value = p.name;
  document.getElementById('pCategory').value = p.category_id || '';
  document.getElementById('pDesc').value = p.description || '';
  document.getElementById('pPrice').value = p.price;
  document.getElementById('pStock').value = p.stock;
  document.getElementById('pStatus').value = p.status;
  document.getElementById('pFav').value = p.is_favorite;
  document.getElementById('pImageUrl').value = p.image || '';
  if (p.image) { document.getElementById('pImagePreview').src = p.image; document.getElementById('pImagePreview').style.display = 'block'; }
  else { document.getElementById('pImagePreview').style.display = 'none'; }
  document.getElementById('productModalTitle').textContent = 'Edit Produk';
  document.getElementById('productModal').classList.add('active');
}

async function saveProduct() {
  const id = document.getElementById('pId').value;
  const name = document.getElementById('pName').value.trim();
  if (!name) { toast('Nama produk wajib diisi', 'error'); return; }

  const btn = document.getElementById('saveProductBtn'); btn.disabled = true; btn.textContent = 'Menyimpan...';
  let imageUrl = document.getElementById('pImageUrl').value;

  // Upload image jika ada file baru
  const fileInput = document.getElementById('pImage');
  if (fileInput.files[0]) {
    try {
      const fd = new FormData(); fd.append('image', fileInput.files[0]);
      const uploadRes = await fetch(BASE + '/api-upload.php', {method: 'POST', headers: {'Authorization': 'Bearer ' + authToken}, body: fd});
      const uploadData = await uploadRes.json();
      if (uploadData.status === 'success') imageUrl = uploadData.image;
      else { toast('Gagal upload foto', 'error'); btn.disabled = false; btn.textContent = 'Simpan'; return; }
    } catch(e) { toast('Gagal upload foto', 'error'); btn.disabled = false; btn.textContent = 'Simpan'; return; }
  }

  const body = {
    id: id || undefined, name,
    category_id: document.getElementById('pCategory').value || null,
    description: document.getElementById('pDesc').value.trim(),
    price: document.getElementById('pPrice').value.replace(/\D/g, ''),
    stock: parseInt(document.getElementById('pStock').value) || 0,
    status: parseInt(document.getElementById('pStatus').value),
    is_favorite: parseInt(document.getElementById('pFav').value),
    image: imageUrl,
  };
  const method = id ? 'PUT' : 'POST';
  const data = await api('api-products.php', {method, body: JSON.stringify(body)});
  if (data.status === 'success') { toast(id ? 'Produk diupdate' : 'Produk ditambah'); closeProductModal(); loadProducts(); } else { toast(data.message || 'Gagal', 'error'); }
  btn.disabled = false; btn.textContent = 'Simpan';
}

async function deleteProduct(id) {
  if (!confirm('Hapus produk ini?')) return;
  const data = await api('api-products.php', {method: 'DELETE', body: JSON.stringify({id})});
  if (data.status === 'success') { toast('Produk dihapus'); loadProducts(); } else { toast(data.message || 'Gagal', 'error'); }
}

// ===== ORDERS =====
async function loadOrders() {
  const date = document.getElementById('orderDate').value;
  const data = await api('api-orders.php?date=' + date);
  if (data.status !== 'success') return;
  const d = data.data;

  // Summary
  document.getElementById('orderSummary').innerHTML =
    '<div class="summary-card"><h3>Total Order</h3><div class="value">' + (d.summary.order_count || 0) + '</div></div>' +
    '<div class="summary-card"><h3>Pendapatan</h3><div class="value">Rp ' + Number(d.summary.total_revenue || 0).toLocaleString('id-ID') + '</div></div>' +
    '<div class="summary-card"><h3>Total Dibayar</h3><div class="value">Rp ' + Number(d.summary.total_paid || 0).toLocaleString('id-ID') + '</div></div>' +
    '<div class="summary-card"><h3>Refund</h3><div class="value" style="color:#e74c3c">Rp ' + Number(d.summary.total_refund || 0).toLocaleString('id-ID') + '</div></div>';

  // Rekap per outlet
  const os = d.outlets_summary || [];
  document.getElementById('outletSummary').innerHTML = os.length
    ? os.map(o => '<div class="summary-card"><h3>' + esc(o.outlet_name || 'Tanpa Outlet') + '</h3><div class="value">Rp ' + Number(o.total_revenue || 0).toLocaleString('id-ID') + '</div><div style="font-size:12px;color:#888">' + o.order_count + ' order</div></div>').join('')
    : '<div class="summary-card"><h3>Belum ada data</h3><div class="value">-</div></div>';

  const orders = d.orders || [];
  const tbody = document.getElementById('ordersBody');
  if (!orders.length) { tbody.innerHTML = '<tr><td colspan="11" class="empty">Tidak ada order hari ini</td></tr>'; return; }
  tbody.innerHTML = orders.map((o, i) => '<tr>' +
    '<td>' + (i + 1) + '</td>' +
    '<td>' + o.created_at + '</td>' +
    '<td>ORD-' + String(o.order_number).padStart(3, '0') + '</td>' +
    '<td>' + esc(o.order_type) + '</td>' +
    '<td>' + esc(o.table_number || '-') + '</td>' +
    '<td>' + esc(o.nama_kasir) + '</td>' +
    '<td style="max-width:200px;font-size:12px">' + esc(o.items_summary || '-') + '</td>' +
    '<td>Rp ' + Number(o.total).toLocaleString('id-ID') + '</td>' +
    '<td>Rp ' + Number(o.payment_amount).toLocaleString('id-ID') + '</td>' +
    '<td>' + (o.status === 'refund' ? '<span class="badge badge-inactive">Refund</span>' : '<span class="badge badge-active">Lunas</span>') + '</td>' +
    '<td>' + (o.status === 'refund'
      ? '<button class="btn btn-sm btn-success" onclick="refundOrder(' + o.id + ', \'cancel_refund\')">Batalkan Refund</button>'
      : '<button class="btn btn-sm btn-danger" onclick="refundOrder(' + o.id + ', \'refund\')">Refund</button>') + '</td>' +
    '</tr>').join('');
}

async function refundOrder(id, action) {
  if (action === 'refund' && !confirm('Tandai order ini sebagai REFUND? Nominal akan dikeluarkan dari pendapatan.')) return;
  if (action === 'cancel_refund' && !confirm('Batalkan refund order ini?')) return;
  const data = await api('api-refund.php', {method: 'POST', body: JSON.stringify({order_id: id, action: action})});
  if (data.status === 'success') { toast('Status order diperbarui'); loadOrders(); }
  else { toast(data.message || 'Gagal', 'error'); }
}

// ===== PAYMENT METHODS =====
async function loadPaymentMethods() {
  const data = await api('api-payment-methods.php');
  allPaymentMethods = data.data || [];
  renderPaymentMethods();
}

function renderPaymentMethods() {
  const tbody = document.getElementById('paymentBody');
  if (!allPaymentMethods.length) { tbody.innerHTML = '<tr><td colspan="8" class="empty">Belum ada metode pembayaran</td></tr>'; return; }
  tbody.innerHTML = allPaymentMethods.map(m => '<tr>' +
    '<td>' + m.id + '</td>' +
    '<td><strong>' + esc(m.name) + '</strong></td>' +
    '<td>' + esc(typeLabel(m.type)) + '</td>' +
    '<td>' + esc(m.bank_name || '-') + '</td>' +
    '<td>' + esc(m.account_name || '-') + '</td>' +
    '<td>' + esc(m.account_number || '-') + '</td>' +
    '<td><span class="badge ' + (m.is_active == 1 ? 'badge-active' : 'badge-inactive') + '">' + (m.is_active == 1 ? 'Aktif' : 'Nonaktif') + '</span></td>' +
    '<td><button class="btn btn-sm btn-success" onclick="togglePaymentActive(' + m.id + ')">' + (m.is_active == 1 ? 'Nonaktifkan' : 'Aktifkan') + '</button> <button class="btn btn-sm btn-warning" onclick="editPaymentMethod(' + m.id + ')">Edit</button> <button class="btn btn-sm btn-danger" onclick="deletePaymentMethod(' + m.id + ')">Hapus</button></td>' +
    '</tr>').join('');
}

function typeLabel(t) {
  const map = {cash: 'Cash', qris: 'QRIS', edc: 'EDC / Kartu', transfer: 'Transfer Bank'};
  return map[t] || t;
}

function openPaymentModal() {
  ['pmId','pmName','pmBank','pmAccountName','pmAccountNumber'].forEach(id => document.getElementById(id).value = '');
  document.getElementById('pmType').value = 'qris';
  document.getElementById('pmActive').value = '1';
  document.getElementById('paymentModalTitle').textContent = 'Tambah Metode Pembayaran';
  document.getElementById('paymentModal').classList.add('active');
}
function closePaymentModal() { document.getElementById('paymentModal').classList.remove('active'); }

function editPaymentMethod(id) {
  const m = allPaymentMethods.find(x => x.id == id); if (!m) return;
  document.getElementById('pmId').value = m.id;
  document.getElementById('pmName').value = m.name;
  document.getElementById('pmType').value = m.type;
  document.getElementById('pmBank').value = m.bank_name || '';
  document.getElementById('pmAccountName').value = m.account_name || '';
  document.getElementById('pmAccountNumber').value = m.account_number || '';
  document.getElementById('pmActive').value = m.is_active;
  document.getElementById('paymentModalTitle').textContent = 'Edit Metode Pembayaran';
  document.getElementById('paymentModal').classList.add('active');
}

async function savePaymentMethod() {
  const id = document.getElementById('pmId').value;
  const name = document.getElementById('pmName').value.trim();
  if (!name) { toast('Nama metode wajib diisi', 'error'); return; }
  const body = {
    id: id || undefined, name,
    type: document.getElementById('pmType').value,
    bank_name: document.getElementById('pmBank').value.trim(),
    account_name: document.getElementById('pmAccountName').value.trim(),
    account_number: document.getElementById('pmAccountNumber').value.trim(),
    is_active: parseInt(document.getElementById('pmActive').value),
    sort_order: 0,
  };
  const method = id ? 'PUT' : 'POST';
  const data = await api('api-payment-methods.php', {method, body: JSON.stringify(body)});
  if (data.status === 'success') { toast(id ? 'Metode diupdate' : 'Metode ditambah'); closePaymentModal(); loadPaymentMethods(); } else { toast(data.message || 'Gagal', 'error'); }
}

async function togglePaymentActive(id) {
  const m = allPaymentMethods.find(x => x.id == id); if (!m) return;
  const body = {
    id: m.id, name: m.name, type: m.type,
    bank_name: m.bank_name, account_name: m.account_name, account_number: m.account_number,
    is_active: m.is_active == 1 ? 0 : 1, sort_order: m.sort_order || 0,
  };
  const data = await api('api-payment-methods.php', {method: 'PUT', body: JSON.stringify(body)});
  if (data.status === 'success') { toast('Status diubah'); loadPaymentMethods(); } else { toast(data.message || 'Gagal', 'error'); }
}

async function deletePaymentMethod(id) {
  if (!confirm('Hapus metode pembayaran ini?')) return;
  const data = await api('api-payment-methods.php', {method: 'DELETE', body: JSON.stringify({id})});
  if (data.status === 'success') { toast('Metode dihapus'); loadPaymentMethods(); } else { toast(data.message || 'Gagal', 'error'); }
}

// ===== OUTLETS =====
async function loadOutlets() {
  const data = await api('api-outlets.php');
  allOutlets = data.data || [];
  renderOutlets();
  renderOutletOptions();
}

function renderOutlets() {
  const tbody = document.getElementById('outletsBody');
  if (!allOutlets.length) { tbody.innerHTML = '<tr><td colspan="5" class="empty">Belum ada outlet</td></tr>'; return; }
  tbody.innerHTML = allOutlets.map(o => '<tr>' +
    '<td>' + o.id + '</td>' +
    '<td><strong>' + esc(o.name) + '</strong></td>' +
    '<td>' + esc(o.address || '-') + '</td>' +
    '<td>' + (o.is_active == 1 ? '<span class="badge badge-active">Aktif</span>' : '<span class="badge badge-inactive">Nonaktif</span>') + '</td>' +
    '<td><button class="btn btn-sm btn-warning" onclick="editOutlet(' + o.id + ')">Edit</button> <button class="btn btn-sm btn-danger" onclick="deleteOutlet(' + o.id + ')">Hapus</button></td>' +
    '</tr>').join('');
}

function renderOutletOptions() {
  document.getElementById('uOutlet').innerHTML = '<option value="">Tanpa Outlet (Pusat)</option>' +
    allOutlets.map(o => '<option value="' + o.id + '">' + esc(o.name) + '</option>').join('');
}

function openOutletModal() {
  document.getElementById('oId').value = '';
  document.getElementById('oName').value = '';
  document.getElementById('oAddress').value = '';
  document.getElementById('oActive').value = '1';
  document.getElementById('outletModalTitle').textContent = 'Tambah Outlet';
  document.getElementById('outletModal').classList.add('active');
}
function closeOutletModal() { document.getElementById('outletModal').classList.remove('active'); }

function editOutlet(id) {
  const o = allOutlets.find(x => x.id == id); if (!o) return;
  document.getElementById('oId').value = o.id;
  document.getElementById('oName').value = o.name;
  document.getElementById('oAddress').value = o.address || '';
  document.getElementById('oActive').value = o.is_active;
  document.getElementById('outletModalTitle').textContent = 'Edit Outlet';
  document.getElementById('outletModal').classList.add('active');
}

async function saveOutlet() {
  const id = document.getElementById('oId').value;
  const name = document.getElementById('oName').value.trim();
  if (!name) { toast('Nama outlet wajib diisi', 'error'); return; }
  const body = { id: id || undefined, name, address: document.getElementById('oAddress').value.trim(), is_active: parseInt(document.getElementById('oActive').value) };
  const method = id ? 'PUT' : 'POST';
  const data = await api('api-outlets.php', {method, body: JSON.stringify(body)});
  if (data.status === 'success') { toast(id ? 'Outlet diupdate' : 'Outlet ditambah'); closeOutletModal(); loadOutlets(); } else { toast(data.message || 'Gagal', 'error'); }
}

async function deleteOutlet(id) {
  if (!confirm('Hapus outlet ini?')) return;
  const data = await api('api-outlets.php', {method: 'DELETE', body: JSON.stringify({id})});
  if (data.status === 'success') { toast('Outlet dihapus'); loadOutlets(); } else { toast(data.message || 'Gagal', 'error'); }
}

// ===== USERS / KASIR =====
async function loadUsers() {
  const data = await api('api-users.php');
  allUsers = data.data || [];
  renderUsers();
}

function renderUsers() {
  const tbody = document.getElementById('usersBody');
  if (!allUsers.length) { tbody.innerHTML = '<tr><td colspan="6" class="empty">Belum ada kasir</td></tr>'; return; }
  tbody.innerHTML = allUsers.map(u => '<tr>' +
    '<td>' + u.id + '</td>' +
    '<td><strong>' + esc(u.name) + '</strong></td>' +
    '<td>' + esc(u.email) + '</td>' +
    '<td>' + esc(u.role) + '</td>' +
    '<td>' + esc(u.outlet_name || '-') + '</td>' +
    '<td><button class="btn btn-sm btn-warning" onclick="editUser(' + u.id + ')">Edit</button> <button class="btn btn-sm btn-danger" onclick="deleteUser(' + u.id + ')">Hapus</button></td>' +
    '</tr>').join('');
}

function openUserModal() {
  document.getElementById('uId').value = '';
  document.getElementById('uName').value = '';
  document.getElementById('uEmail').value = '';
  document.getElementById('uPassword').value = '';
  document.getElementById('uRole').value = 'kasir';
  document.getElementById('uOutlet').value = '';
  document.getElementById('userModalTitle').textContent = 'Tambah Kasir';
  document.getElementById('userModal').classList.add('active');
}
function closeUserModal() { document.getElementById('userModal').classList.remove('active'); }

function editUser(id) {
  const u = allUsers.find(x => x.id == id); if (!u) return;
  document.getElementById('uId').value = u.id;
  document.getElementById('uName').value = u.name;
  document.getElementById('uEmail').value = u.email;
  document.getElementById('uPassword').value = '';
  document.getElementById('uRole').value = u.role;
  document.getElementById('uOutlet').value = u.outlet_id || '';
  document.getElementById('userModalTitle').textContent = 'Edit Kasir';
  document.getElementById('userModal').classList.add('active');
}

async function saveUser() {
  const id = document.getElementById('uId').value;
  const name = document.getElementById('uName').value.trim();
  const email = document.getElementById('uEmail').value.trim();
  const password = document.getElementById('uPassword').value;
  if (!name || !email) { toast('Nama dan email wajib diisi', 'error'); return; }
  if (!id && password.length < 6) { toast('Password minimal 6 karakter', 'error'); return; }
  const body = {
    id: id || undefined, name, email,
    password: password || undefined,
    role: document.getElementById('uRole').value,
    outlet_id: document.getElementById('uOutlet').value || null,
  };
  const method = id ? 'PUT' : 'POST';
  const data = await api('api-users.php', {method, body: JSON.stringify(body)});
  if (data.status === 'success') { toast(id ? 'Kasir diupdate' : 'Kasir ditambah'); closeUserModal(); loadUsers(); } else { toast(data.message || 'Gagal', 'error'); }
}

async function deleteUser(id) {
  if (!confirm('Hapus akun ini?')) return;
  const data = await api('api-users.php', {method: 'DELETE', body: JSON.stringify({id})});
  if (data.status === 'success') { toast('Akun dihapus'); loadUsers(); } else { toast(data.message || 'Gagal', 'error'); }
}

// ===== UTILS =====
function esc(s) { const d = document.createElement('div'); d.textContent = s; return d.innerHTML; }
</script>
</body>
</html>