<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 1) {
    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();
}

// Capture toast messages
$successMsg = $_SESSION['flash']['supplier_success'] ?? '';
$errorMsg = $_SESSION['flash']['supplier_error'] ?? '';
unset($_SESSION['flash']['supplier_success'], $_SESSION['flash']['supplier_error']);

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

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

// Fetch suppliers with limit
$sql = "SELECT * FROM suppliers ORDER BY supplier_name ASC LIMIT ? OFFSET ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $limit, $offset);
$stmt->execute();
$suppliers = $stmt->get_result();
$stmt->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Suppliers – Digital POS</title>
  <link rel="stylesheet" href="../../css/dashboard.css"/>
  <style>
    /* EXACT same style as User Management page */
    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;
    }
    .add-user {
      background: #ff6f00;
      color: white;
      padding: 10px 18px;
      border: none;
      border-radius: 25px;
      font-weight: bold;
      cursor: pointer;
      transition: background 0.3s;
      margin-bottom: 20px;
      display: inline-block;
      white-space: nowrap;
    }
    .add-user:hover {
      background: #e65c00;
    }
    table.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;
    }
    table.user-table th, table.user-table td {
      padding: 14px 16px;
      text-align: left;
      border-bottom: 1px solid rgba(255,255,255,0.1);
    }
    table.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 {
      margin-right: 12px;
      font-size: 14px;
      cursor: pointer;
      font-weight: 600;
      white-space: nowrap;
      text-decoration: none;
      transition: color 0.3s ease;
      color: #ff6f00; /* orange for Edit */
      display: inline-block;
    }
    .actions a.edit {
      color: #ff6f00;
    }
    .actions a.edit:hover {
      color: #e65c00;
    }
    .actions a.delete {
      color: #f44336;
    }
    .actions a.delete:hover {
      color: #d32f2f;
    }

    #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; }

    @media (max-width: 768px) {
      table.user-table th, table.user-table td {
        font-size: 13px;
        padding: 10px;
      }
      .actions a {
        font-size: 12px;
        margin-right: 8px;
      }
    }
  </style>
</head>
<body>
<div class="overlay"></div>
<div id="toast"></div>

<div class="content">
  <h2>Suppliers</h2>

  <button onclick="location.href='add_supplier.php'" class="add-user">+ Add New Supplier</button>

  <table class="user-table">
    <thead>
      <tr>
        <th>Supplier Name</th>
        <th>Contact Person</th>
        <th>Phone</th>
        <th>Email</th>
        <th>Address</th>
        <th>Tax Pin (TPIN)</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      <?php if ($suppliers && $suppliers->num_rows > 0): ?>
        <?php while ($supplier = $suppliers->fetch_assoc()): ?>
          <tr>
            <td><?= htmlspecialchars($supplier['supplier_name']) ?></td>
            <td><?= htmlspecialchars($supplier['contact_person']) ?></td>
            <td><?= htmlspecialchars($supplier['phone']) ?></td>
            <td><?= htmlspecialchars($supplier['email']) ?></td>
            <td><?= nl2br(htmlspecialchars($supplier['address'])) ?></td>
            <td><?= htmlspecialchars($supplier['t_pin']) ?></td>
            <td class="actions">
              <a href="edit_supplier.php?id=<?= $supplier['id'] ?>" class="edit">Edit</a>
              <a href="delete_supplier.php?id=<?= $supplier['id'] ?>" class="delete" onclick="return confirm('Are you sure you want to delete this supplier?');">Delete</a>
            </td>
          </tr>
        <?php endwhile; ?>
      <?php else: ?>
        <tr><td colspan="7" style="text-align:center;">No suppliers found.</td></tr>
      <?php endif; ?>
    </tbody>
  </table>

  <!-- Pagination -->
  <div style="text-align:center; margin: 20px 0;">
    <?php for ($p=1; $p <= $totalPages; $p++): ?>
      <a href="?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; ?>
</script>
</body>
</html>
