<?php
ob_start();
// category_admin.php
header('Content-Type: application/json; charset=utf-8');

include_once('configa.php'); // উপরে দেখানো configa.php

// --- Simple router for AJAX actions ---
$method = $_SERVER['REQUEST_METHOD'];
$action = $_REQUEST['action'] ?? '';

if ($method === 'GET' && $action === 'list') {
    // Return all categories as JSON
    $sql = "SELECT id, category_list, submit_date, edit_date FROM category ORDER BY id DESC";
    $res = $conn->query($sql);
    $rows = [];
    while ($r = $res->fetch_assoc()) $rows[] = $r;
    echo json_encode(['status'=>'ok','data'=>$rows]);
    exit;
}

if ($method === 'POST' && $action === 'create') {
    $cat = trim($_POST['category_list'] ?? '');
    if ($cat === '') {
        echo json_encode(['status'=>'error','message'=>'Category empty']);
        exit;
    }
    $stmt = $conn->prepare("INSERT INTO category (category_list, submit_date) VALUES (?, NOW())");
    $stmt->bind_param('s', $cat);
    if ($stmt->execute()) {
        echo json_encode(['status'=>'ok','id'=>$stmt->insert_id]);
    } else {
        echo json_encode(['status'=>'error','message'=>$stmt->error]);
    }
    exit;
}

if ($method === 'POST' && $action === 'update') {
    $id = intval($_POST['id'] ?? 0);
    $cat = trim($_POST['category_list'] ?? '');
    if ($id <= 0 || $cat === '') {
        echo json_encode(['status'=>'error','message'=>'Invalid input']);
        exit;
    }
    $stmt = $conn->prepare("UPDATE category SET category_list = ?, edit_date = NOW() WHERE id = ?");
    $stmt->bind_param('si', $cat, $id);
    if ($stmt->execute()) {
        echo json_encode(['status'=>'ok']);
    } else {
        echo json_encode(['status'=>'error','message'=>$stmt->error]);
    }
    exit;
}

if ($method === 'POST' && $action === 'delete') {
    $id = intval($_POST['id'] ?? 0);
    if ($id <= 0) {
        echo json_encode(['status'=>'error','message'=>'Invalid id']);
        exit;
    }
    $stmt = $conn->prepare("DELETE FROM category WHERE id = ?");
    $stmt->bind_param('i', $id);
    if ($stmt->execute()) {
        echo json_encode(['status'=>'ok']);
    } else {
        echo json_encode(['status'=>'error','message'=>$stmt->error]);
    }
    exit;
}

// If not AJAX action -> show HTML UI
header('Content-Type: text/html; charset=utf-8');
?>

<style>

    @font-face {
      font-family: 'SutonnyOMJ';
      src: url('font/SutonnyOMJ.ttf') format('truetype');
      font-display: swap;
    }

    @font-face {
      font-family: 'SutonnyMJ';
      src: url('font/SUTOM___0.TTF') format('truetype');
      font-display: swap;
    }



<style>
@font-face {
  font-family: 'SutonnyOMJ';
  src: url('font/SutonnyOMJ.ttf') format('truetype');
  font-display: swap;
}
@font-face {
  font-family: 'SutonnyMJ';
  src: url('font/SUTOM___0.TTF') format('truetype');
  font-display: swap;
}

/* --- General --- */
body{
  font-family: 'SutonnyOMJ', Arial, sans-serif;
  margin:0;
  padding:20px;
  background:#f0f2f5;
  color:#333;
}
h2{text-align:center; margin-bottom:20px;}

/* --- Card --- */
.card{
  background:#fff;
  border-radius:10px;
  padding:20px;
  box-shadow:0 4px 12px rgba(0,0,0,0.08);
  margin-bottom:20px;
}

/* --- Table --- */
table{
  width:100%;
  border-collapse:collapse;
  margin-top:10px;
}
th, td{
  padding:10px;
  border-bottom:1px solid #eee;
  text-align:left;
}
th{background:#f7f9fc;}
td input[type="text"]{
  width:100%;
  padding:6px 8px;
  box-sizing:border-box;
  border:1px solid #ccc;
  border-radius:4px;
}

/* --- Buttons --- */
button{
  padding:6px 12px;
  border-radius:6px;
  cursor:pointer;
  font-size:14px;
  transition:all 0.2s;
}
button:hover{opacity:0.9;}
.btn-green{background:#16a34a;color:#fff;border:0;}
.btn-red{background:#ef4444;color:#fff;border:0;}
.btn-outline{background:#fff;border:1px solid #ccc;color:#333;}
.btn-small{padding:4px 8px; font-size:13px;}

/* --- Row Actions --- */
.row-actions button{margin-right:5px; margin-bottom:3px;}

/* --- Add Row --- */
.add-row{
  display:flex;
  gap:10px;
  margin-top:12px;
  flex-wrap:wrap;
}
.add-row input[type="text"]{flex:1;}
.add-row button{flex:none;}

/* --- Small Text --- */
.small{font-size:12px;color:#666;}
</style>

    


<div class="card">
  <center><h2>Category তালিকা ও পরিচালনা</h2></center>



  <div id="list-wrap" style="margin-top:12px;">
    <table id="cat-table">
      <thead>
        <tr>
          <th>#</th>
          <th>Category</th>
          <th>Submit Date</th>
          <th>Edit Date</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody id="cat-body">
        <!-- rows injected here -->
      </tbody>
    </table>
  </div>

  <!-- Add row placeholder -->
  <div id="add-area" style="margin-top:12px;"></div>


  <div style="display:flex; justify-content:flex-end; gap:10px; margin-bottom:10px;">
    <button id="btn-refresh" class="btn-outline btn-small">Refresh</button>
    <button id="btn-add" class="btn-green btn-small">Add</button>
  </div>


</div>

<script>
const apiUrl = location.pathname + '?action=';

async function fetchList(){
  const res = await fetch(apiUrl + 'list');
  const j = await res.json();
  if (j.status !== 'ok') return alert('Error loading');
  const body = document.getElementById('cat-body');
  body.innerHTML = '';
  j.data.forEach((r, idx) => {
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td>${r.id}</td>
      <td class="cat-text" data-id="${r.id}">${escapeHtml(r.category_list)}</td>
      <td class="small">${r.submit_date ?? ''}</td>
      <td class="small">${r.edit_date ?? ''}</td>
      <td class="row-actions">
        <button class="btn-outline" data-action="edit" data-id="${r.id}">Edit</button>
        <button class="btn-red" data-action="delete" data-id="${r.id}">Delete</button>
      </td>
    `;
    body.appendChild(tr);
  });
}

function escapeHtml(text){
  if (!text) return '';
  return text.replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;').replaceAll('"','&quot;');
}

document.getElementById('btn-refresh').addEventListener('click', fetchList);

document.getElementById('btn-add').addEventListener('click', () => {
  const addArea = document.getElementById('add-area');
  addArea.innerHTML = `
    <div class="add-row card" id="temp-add">
      <input type="text" id="new-cat" placeholder="নতুন ক্যাটাগরির নাম লিখুন">
      <div style="margin-top:8px">
        <button id="save-new" class="btn-green">Save</button>
        <button id="cancel-new" class="btn-outline">Cancel</button>
      </div>
    </div>
  `;
  document.getElementById('new-cat').focus();
  document.getElementById('cancel-new').addEventListener('click', ()=> addArea.innerHTML = '');
  document.getElementById('save-new').addEventListener('click', async ()=>{
    const val = document.getElementById('new-cat').value.trim();
    if (!val) return alert('খালি নাম দিন না');
    const fd = new FormData();
    fd.append('action','create');
    fd.append('category_list', val);
    const res = await fetch(location.pathname + '?action=create', {method:'POST', body:fd});
    const j = await res.json();
    if (j.status === 'ok') {
      addArea.innerHTML = '';
      fetchList();
    } else {
      alert('Error: ' + (j.message || 'Failed'));
    }
  });
});

// Delegate edit/delete buttons
document.getElementById('cat-table').addEventListener('click', async (e) => {
  const btn = e.target.closest('button');
  if (!btn) return;
  const action = btn.getAttribute('data-action');
  const id = btn.getAttribute('data-id');
  if (action === 'delete') {
    if (!confirm('মুছে ফেলতে চাও?')) return;
    const fd = new FormData();
    fd.append('action','delete');
    fd.append('id', id);
    const res = await fetch(location.pathname + '?action=delete', {method:'POST', body:fd});
    const j = await res.json();
    if (j.status === 'ok') fetchList(); else alert('Error: ' + (j.message || ''));
  }
  if (action === 'edit') {
    // replace category cell with input
    const td = btn.closest('tr').querySelector('.cat-text');
    const cur = td.textContent;
    td.innerHTML = `<input type="text" value="${cur}" style="width:100%" />`;
    btn.textContent = 'Save';
    btn.setAttribute('data-action','save');
    // add cancel button
    let cancelBtn = btn.parentElement.querySelector('[data-action="cancel"]');
    if (!cancelBtn) {
      const c = document.createElement('button');
      c.className = 'btn-outline';
      c.textContent = 'Cancel';
      c.setAttribute('data-action','cancel');
      c.setAttribute('data-id', id);
      btn.parentElement.appendChild(c);
      c.addEventListener('click', () => {
        fetchList();
      });
    }
  } else if (action === 'save') {
    const tr = btn.closest('tr');
    const id = btn.getAttribute('data-id');
    const input = tr.querySelector('input[type="text"]');
    const val = input.value.trim();
    if (!val) return alert('নাম লিখো');
    const fd = new FormData();
    fd.append('action','update');
    fd.append('id', id);
    fd.append('category_list', val);
    const res = await fetch(location.pathname + '?action=update', {method:'POST', body:fd});
    const j = await res.json();
    if (j.status === 'ok') {
      fetchList();
    } else {
      alert('Error: ' + (j.message || ''));
    }
  }
});

fetchList();
</script>






<?php
// End capturing the output and store it in a variable
$product_add_display_content = ob_get_clean();

// Now include frameForAll.php, which will use $catagory_display_content
include("frameForAll.php");

// mysqli_close($conn); // You might want to close the connection after all database operations
ob_end_flush();
?>




<!DOCTYPE html>
<html>
<head>

  <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

<meta name="theme-color" content="#FF0000">
    
<title>অনলাইন শপ</title>
    

  
</head>
<body>


<style type="text/css">




</style>

<!----------------------------->
<script>
  flatpickr("#start_date", {
    dateFormat: "d/m/Y", // DD/MM/YYYY format
    position: "below"     // Force show calendar below
  });

  flatpickr("#end_date", {
    dateFormat: "d/m/Y",
    position: "below"
  });
</script>

<!-- ------------------------- -->
  

</body>
</html>