<?php
session_start();
if (!isset($_SESSION['role_id']) || !in_array($_SESSION['role_id'], [1, 2])) {
    header("Location: ../../index.php");
    exit();
}

include('../../includes/config.php');
include('../../includes/header.php');

// Helper: log errors
function logError($conn, $message) {
    $uid = $_SESSION['user_id'] ?? null;
    $stmt = $conn->prepare("INSERT INTO error_log (message, user_id) VALUES (?, ?)");
    $stmt->bind_param("si", $message, $uid);
    $stmt->execute();
    $stmt->close();
}

// Helper: log audit
function logAudit($conn, $action, $details, $module = 'categories') {
    $stmt = $conn->prepare("INSERT INTO audit_log (user_id, role_id, action, details, module, created_at, device_info)
        VALUES (?, ?, ?, ?, ?, NOW(), ?)");
    $jsonDetails = json_encode($details);
    $device = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
    $stmt->bind_param("iissss", $_SESSION['user_id'], $_SESSION['role_id'], $action, $jsonDetails, $module, $device);
    $stmt->execute();
    $stmt->close();
}

// Capture toast messages
$successMsg = $_GET['success'] ?? '';
$errorMsg = $_GET['error'] ?? '';
if ($errorMsg) logError($conn, $errorMsg);

// Pagination settings
$limit = 15;
$page = max(1, intval($_GET['page'] ?? 1));
$offset = ($page - 1) * $limit;

// Sorting settings
$allowedSortCols = ['id', 'category_name', 'created_at'];
$sortBy = in_array($_GET['sort'] ?? '', $allowedSortCols) ? $_GET['sort'] : 'created_at';
$sortDir = ($_GET['dir'] ?? '') === 'desc' ? 'DESC' : 'ASC';

// Count total categories
$totalSql = "SELECT COUNT(*) FROM categories";
$stmt = $conn->prepare($totalSql);
$stmt->execute();
$stmt->bind_result($totalRows);
$stmt->fetch();
$stmt->close();
$totalPages = ceil($totalRows / $limit);

// Fetch categories with limit and sorting
$sql = "SELECT * FROM categories ORDER BY $sortBy $sortDir LIMIT ? OFFSET ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $limit, $offset);
$stmt->execute();
$categories = $stmt->get_result();
$stmt->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <title>Manage Categories – Digital POS</title>
  <link rel="stylesheet" href="../../css/dashboard.css"/>
  <style>
    /* === EXACT same styles as user management === */
    body, html {
      margin: 0; padding: 0;
      font-family: 'Segoe UI', sans-serif;
      background: url('../../images/profile.jpg') no-repeat center center fixed;
      background-size: cover;
      color: white;
      min-height: 100vh;
      overflow-x: hidden;
    }
    .overlay {
      position: fixed;
      top: 0; left: 0;
      width: 100%; height: 100%;
      background: rgba(0,0,0,0.6);
      z-index: -1;
    }
    .content {
      margin: 100px auto 40px auto;
      padding: 30px 40px;
      max-width: 1200px;
      backdrop-filter: blur(15px);
      background: rgba(255, 255, 255, 0.08);
      border-radius: 20px;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
    }
    h2 {
      text-align: center;
      margin-bottom: 30px;
      font-size: 1.8rem;
    }
    .user-controls {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 25px;
      flex-wrap: wrap;
      gap: 12px;
    }
    .user-controls input[type="text"], .user-controls textarea {
      padding: 10px;
      width: 280px;
      border-radius: 10px;
      border: none;
      outline: none;
      background: rgba(255,255,255,0.1);
      color: white;
      box-shadow: inset 0 0 5px rgba(255,255,255,0.2);
      font-size: 14px;
      resize: vertical;
    }
    .user-controls textarea {
      height: 60px;
      max-width: 280px;
    }
    .add-user {
      background: #ff6f00;
      color: white;
      padding: 10px 18px;
      border: none;
      border-radius: 25px;
      font-weight: bold;
      cursor: pointer;
      transition: background 0.3s;
      white-space: nowrap;
    }
    .add-user:hover {
      background: #e65c00;
    }
    .user-table {
      width: 100%;
      border-collapse: collapse;
      background: rgba(0,0,0,0.3);
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 0 12px rgba(0,0,0,0.6);
      font-size: 0.95rem;
    }
    .user-table th, .user-table td {
      padding: 14px 16px;
      text-align: left;
      border-bottom: 1px solid rgba(255,255,255,0.1);
    }
    .user-table th {
      background: rgba(255,111,0,0.9);
    }
    tbody tr:hover {
      background: rgba(255,111,0,0.1);
    }

    /* ACTION LINKS STYLE: text only, no button styling */
    .actions a, .actions button {
      background: none;
      border: none;
      padding: 0;
      margin-right: 12px;
      font-size: 14px;
      cursor: pointer;
      font-weight: 600;
      white-space: nowrap;
      text-decoration: none;
      transition: color 0.3s ease;
      display: inline-block;
      color: #ff6f00; /* default orange for edit */
    }
    .actions a.edit {
      color: #ff6f00;
    }
    .actions a.edit:hover {
      color: #e65c00;
    }
    .actions a.delete, .actions button.delete {
      color: #f44336;
    }
    .actions a.delete:hover, .actions button.delete:hover {
      color: #d32f2f;
    }

    @media (max-width: 768px) {
      .user-controls {
        flex-direction: column;
        align-items: flex-start;
      }
      .user-controls input[type="text"], .user-controls textarea {
        width: 100%;
        max-width: none;
      }
      .user-table th, .user-table td {
        font-size: 13px;
        padding: 10px;
      }
    }
    #toast {
      position: fixed; top: 20px; right: 20px;
      min-width: 240px;
      padding: 12px 20px;
      border-radius: 8px;
      font-weight: bold;
      box-shadow: 0 4px 8px rgba(0,0,0,0.4);
      display: none;
      z-index: 999;
      color: white;
    }
    #toast.success { background: #4caf50; }
    #toast.error { background: #f44336; }
    th.sortable { cursor: pointer; }
    th.sortable:after { content: ' ↕'; font-size: .8em; color: #ddd; }
    th.sortable.asc:after { content: ' ↑'; }
    th.sortable.desc:after { content: ' ↓'; }
  </style>
</head>
<body>
<div class="overlay"></div>
<div id="toast"></div>

<div class="content">
  <h2>Manage Categories</h2>

  <div class="user-controls">
    <form id="addCategoryForm" style="display:flex; flex-wrap: wrap; gap:12px; align-items:center; margin:0;">
      <input type="text" name="category_name" placeholder="Category Name" required />
      <textarea name="description" placeholder="Description (optional)"></textarea>
      <button type="submit" class="add-user">Add Category</button>
    </form>
  </div>

  <table class="user-table">
    <thead>
      <tr>
        <?php
          $columns = ['id'=>'ID', 'category_name'=>'Name', 'description'=>'Description', 'created_at'=>'Created'];
          foreach ($columns as $col => $label) {
            $dirToggle = ($sortBy==$col && strtoupper($sortDir)=='ASC') ? 'desc' : 'asc';
            $cls = 'sortable' . ($sortBy==$col ? ' '.strtolower($sortDir) : '');
            echo "<th class=\"$cls\" data-col=\"$col\" data-dir=\"$dirToggle\">$label</th>";
          }
        ?>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody id="categoryTableBody">
      <?php if ($categories->num_rows): while ($cat = $categories->fetch_assoc()): ?>
        <tr>
          <td><?= $cat['id'] ?></td>
          <td><?= htmlspecialchars($cat['category_name']) ?></td>
          <td><?= htmlspecialchars($cat['description']) ?></td>
          <td><?= date('d M Y', strtotime($cat['created_at'])) ?></td>
          <td class="actions">
            <a href="edit_category.php?id=<?= $cat['id'] ?>" class="edit">Edit</a>
            <a href="javascript:void(0);" class="delete" onclick="deleteCategory(<?= $cat['id'] ?>)">Delete</a>
          </td>
        </tr>
      <?php endwhile; else: ?>
        <tr><td colspan="5" style="text-align:center;">No categories found.</td></tr>
      <?php endif; ?>
    </tbody>
  </table>

  <div style="text-align:center; margin:20px 0;">
    <?php for ($p=1; $p<=$totalPages; $p++): ?>
      <a href="?<?= http_build_query(array_merge($_GET, ['page'=>$p])) ?>"
         style="margin:0 5px; <?= $p==$page?'font-weight:bold; text-decoration:underline':'' ?>">
        <?= $p ?>
      </a>
    <?php endfor; ?>
  </div>
</div>

<?php include('../../includes/footer.php'); ?>

<script>
  function showToast(msg, type='success') {
    const t = document.getElementById('toast');
    t.textContent = msg;
    t.className = type;
    t.style.display = 'block';
    setTimeout(() => t.style.display = 'none', 3500);
  }
  <?php if ($successMsg): ?> showToast("<?= addslashes($successMsg) ?>",'success'); <?php endif; ?>
  <?php if ($errorMsg): ?> showToast("<?= addslashes($errorMsg) ?>",'error'); <?php endif; ?>

  document.querySelectorAll('th.sortable').forEach(th => {
    th.addEventListener('click', () => {
      const col = th.dataset.col, dir = th.dataset.dir;
      const params = new URLSearchParams(window.location.search);
      params.set('sort', col);
      params.set('dir', dir);
      params.set('page', 1);
      window.location.search = params.toString();
    });
  });

  document.getElementById('addCategoryForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    const form = e.target;
    const formData = new FormData(form);
    try {
      const res = await fetch('create_category.php', {
        method: 'POST',
        body: formData
      });
      const data = await res.json();
      if(data.success) {
        showToast(data.message, 'success');
        setTimeout(() => location.reload(), 1500);
      } else {
        showToast(data.message || 'Failed to add category', 'error');
      }
    } catch {
      showToast('Network error adding category', 'error');
    }
  });

  async function deleteCategory(id) {
    if(!confirm('Delete this category?')) return;
    try {
      const resp = await fetch('delete_category.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: `id=${id}`
      });
      const data = await resp.json();
      if(data.success) {
        showToast(data.message, 'success');
        document.querySelector(`a.delete[onclick="deleteCategory(${id})"]`).closest('tr').remove();
      } else {
        showToast(data.message || 'Delete failed', 'error');
      }
    } catch {
      showToast('Network error deleting category', 'error');
    }
  }
</script>
</body>
</html>
