<?php
// Koneksi ke database
session_start();

// Ambil informasi user yang sedang login
$userRole = $_SESSION['role']; // 'user' atau 'admin'
$username = $_SESSION['username']; // Menambahkan username dari session

// Jika username adalah root, tampilkan nama yang lebih presentable
$displayName = ($username === 'root') ? 'Admin' : $username;

// Cek apakah session 'user_id' ada, yang berarti pengguna sudah login
if (!isset($_SESSION['user_id'])) {
  // Jika session tidak ada, arahkan pengguna ke halaman login
  header("Location: /ayula-store/index.php");
  exit();
}

// Function to check user permissions
function hasPermission($action, $userRole) {
    switch ($action) {
        case 'view':
            // Both admin and user can view product details
            return true;
        case 'edit':
        case 'delete':
            // Only admin can edit and delete
            return $userRole === 'admin';
        default:
            return false;
    }
}

// Database connection
include('../../routes/db_conn.php');

// Ambil parameter search jika ada
$search = isset($_GET['search']) ? $_GET['search'] : '';

$sql = "SELECT bk.kode_barang, bk.nama_barang, jb.nama_jenis, bk.stok, bk.harga, bk.kode_barang, bk.gambar 
        FROM barang_kasir bk 
        JOIN jenis_barang jb ON bk.id_jenis = jb.id_jenis";

if (!empty($search)) {
    $sql .= " WHERE bk.nama_barang LIKE '%$search%' OR jb.nama_jenis LIKE '%$search%'";
}

$result = $conn->query($sql);

// Handle delete operation - only for admin role
if (isset($_GET['delete_id'])) {
    if (hasPermission('delete', $userRole)) {
        $id = $_GET['delete_id'];
        $sql = "DELETE FROM barang_kasir WHERE kode_barang = '$id'";

        if ($conn->query($sql) === TRUE) {
            header("Location: /ayula-store/views/barang-kasir/?success=1");
            exit();
        } else {
            header("Location: /ayula-store/views/barang-kasir/?success=0");
            exit();
        }
    } else {
        // If user tries to delete without permission, redirect with error
        header("Location: /ayula-store/views/barang-kasir/?error=Anda tidak memiliki izin untuk menghapus barang");
        exit();
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta
    name="viewport"
    content="width=device-width, initial-scale=1.0, user-scalable=0" />
  <meta name="description" content="POS - Bootstrap Admin Template" />
  <meta
    name="keywords"
    content="admin, estimates, bootstrap, business, corporate, creative, invoice, html5, responsive, Projects" />
  <meta name="author" content="Dreamguys - Bootstrap Admin Template" />
  <meta name="robots" content="noindex, nofollow" />
  <title>Dreams Pos admin template</title>

  <link rel="shortcut icon" type="image/x-icon" href="../../src/img/smallest-ayula.png">

  <link rel="stylesheet" href="/ayula-store/bootstrap/assets/css/bootstrap.min.css" />

  <link rel="stylesheet" href="/ayula-store/bootstrap/assets/css/animate.css" />

  <link rel="stylesheet" href="/ayula-store/bootstrap/assets/plugins/select2/css/select2.min.css" />

  <link rel="stylesheet" href="/ayula-store/bootstrap/assets/css/dataTables.bootstrap4.min.css" />

  <link
    rel="stylesheet"
    href="/ayula-store/bootstrap/assets/plugins/fontawesome/css/fontawesome.min.css" />
  <link rel="stylesheet" href="/ayula-store/bootstrap/assets/plugins/fontawesome/css/all.min.css" />

  <link rel="stylesheet" href="/ayula-store/bootstrap/assets/css/style.css" />
</head>

<body>
  <div id="global-loader">
    <div class="whirly-loader"></div>
  </div>

  <div class="main-wrapper">
    <div class="header">
      <div class="header-left active">
        <a href="/ayula-store/views/dashboard/" class="logo">
          <img src="../../src/img/logoayula.png" alt="" />
        </a>
        <a href="/ayula-store/views/dashboard/" class="logo-small">
          <img src="../../src/img/smallest-ayula.png" alt="" />
        </a>
        <a id="toggle_btn" href="javascript:void(0);"> </a>
      </div>

      <a id="mobile_btn" class="mobile_btn" href="#sidebar">
        <span class="bar-icon">
          <span></span>
          <span></span>
          <span></span>
        </span>
      </a>

      <ul class="nav user-menu">
        <li class="nav-item dropdown has-arrow main-drop">
          <a href="javascript:void(0);" class="dropdown-toggle nav-link userset" data-bs-toggle="dropdown">
            <span class="user-img"><img src="../../src/img/userprofile.png" alt="">
              <span class="status online"></span></span>
          </a>
          <div class="dropdown-menu menu-drop-user">
            <div class="profilename">
              <div class="profileset">
                <span class="user-img"><img src="../../src/img/userprofile.png" alt="">
                  <span class="status online"></span></span>
                <div class="profilesets">
                  <h6><?php echo $userRole == 'admin' ? 'Admin' : 'Karyawan'; ?></h6>
                  <h5><?php echo htmlspecialchars($displayName); ?></h5>
                </div>
              </div>
              <hr class="m-0" />
              <a class="dropdown-item" href="/ayula-store/views/report-issue/">
                <img src="../../src/img/warning.png" class="me-2" alt="img" /> Laporkan Masalah
              </a>
              <hr class="m-0" />
              <a class="dropdown-item logout pb-0" href="../../views/logout.php"><img
                  src="../../bootstrap/assets/img/icons/log-out.svg" class="me-2" alt="img" />Keluar</a>
            </div>
          </div>
        </li>
      </ul>

      <div class="dropdown mobile-user-menu">
        <a href="javascript:void(0);" class="nav-link dropdown-toggle" data-bs-toggle="dropdown"
          aria-expanded="false"><i class="fa fa-ellipsis-v"></i></a>
        <div class="dropdown-menu dropdown-menu-right">
          <a class="dropdown-item" href="/ayula-store/views/report-issue/">
            <i class="fa fa-cog me-2"></i> Laporkan Masalah
          </a>
          <hr class="m-0" />
          <a class="dropdown-item logout pb-0" href="../../views/logout.php"><img
              src="../../bootstrap/assets/img/icons/log-out.svg" class="me-2" alt="img" />Keluar</a>
        </div>
      </div>
    </div>

    <div class="sidebar" id="sidebar">
      <div class="sidebar-inner slimscroll">
        <div id="sidebar-menu" class="sidebar-menu">
          <ul>
            <li>
              <a href="/ayula-store/views/dashboard/"><img
                  src="../../bootstrap/assets/img/icons/dashboard.svg" alt="img" /><span>
                  Dashboard</span>
              </a>
            </li>
            <li>
              <a href="/ayula-store/views/transaction/"><img src="../../bootstrap/assets/img/icons/sales1.svg"
                  alt="img" /><span>
                  POS</span></a>
            </li>
            <li class="submenu">
              <a href="javascript:void(0);"><img src="../../bootstrap/assets/img/icons/product.svg" alt="img" /><span>
                  Produk</span>
                <span class="menu-arrow"></span></a>
              <ul>
                <li><a href="/ayula-store/views/barang-kasir/" class="active">Daftar Produk Kasir</a></li>
              </ul>
            </li>

            <li class="submenu">
              <a href="javascript:void(0);"><img src="../../bootstrap/assets/img/icons/time.svg" alt="img" /><span>
                  Laporan</span>
                <span class="menu-arrow"></span></a>
              <ul>
                <li><a href="/ayula-store/views/report/sales-report/">Laporan Penjualan</a></li>
                <?php if ($userRole == 'admin') { ?>
                  <li><a href="/ayula-store/views/report/popular-products/">Produk Terlaris</a></li>
                <?php } ?>
              </ul>
            </li>
            <li class="submenu">
              <a href="javascript:void(0);"><img src="../../bootstrap/assets/img/icons/users1.svg" alt="img" /><span>
                  Pengguna</span>
                <span class="menu-arrow"></span></a>
              <ul>
                <?php if ($userRole == 'admin') { ?>
                  <li><a href="/ayula-store/views/users/add-user.php">Pengguna Baru</a></li>
                <?php } ?>
                <li><a href="/ayula-store/views/users/">Daftar Pengguna</a></li>
              </ul>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <div class="page-wrapper">
      <div class="content">
        <div class="page-header">
          <div class="page-title">
            <h4>Daftar Barang Kasir</h4>
            <h6>Kelola Barang di Kasir</h6>
          </div>
        </div>

        <div class="card">
          <div class="card-body">
            <div class="table-top">
              <div class="search-set">
                <div class="search-path">
                    <span><img src="/ayula-store/bootstrap/assets/img/icons/closes.svg" alt="img" /></span>
                  </a>
                </div>
                <div class="search-input" disable>
                </div>
              </div>
            </div>
           
            <!-- Tabel Data Barang Kasir -->
            <div class="table-responsive">
                <table class="table datanew">
                    <thead>
                        <tr>
                            <th>Kode Barang</th>
                            <th>Nama Barang</th>
                            <th>Jenis</th>
                            <th>Stok</th>
                            <th>Harga</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>

                    <?php
                    if ($result->num_rows > 0) {
                        while ($row = $result->fetch_assoc()) {
                            echo "<tr>
                                    <td>{$row['kode_barang']}</td>
                                    <td>{$row['nama_barang']}</td>
                                    <td>{$row['nama_jenis']}</td>
                                    <td>{$row['stok']}</td>
                                    <td>Rp " . number_format($row['harga'], 0, ',', '.') . "</td>
                                    <td>";
                            
                            // View button - visible to all users
                            if (hasPermission('view', $userRole)) {
                                echo "<a class='me-3' href='/ayula-store/views/barang-kasir/product-details.php?id={$row['kode_barang']}'>
                                        <img src='/ayula-store/bootstrap/assets/img/icons/eye.svg' alt='Lihat Detail' />
                                      </a>";
                            }
                            
                            // Edit button - visible only to admin
                            if (hasPermission('edit', $userRole)) {
                                echo "<a class='me-3' href='/ayula-store/views/barang-kasir/editproducts.php?id={$row['kode_barang']}'>
                                        <img src='/ayula-store/bootstrap/assets/img/icons/edit.svg' alt='Edit' />
                                      </a>";
                            }
                            
                            // Delete button - visible only to admin
                            if (hasPermission('delete', $userRole)) {
                                echo "<a class='me-3' href='javascript:void(0);' onclick='confirmDelete(\"{$row['kode_barang']}\")'>
                                        <img src='/ayula-store/bootstrap/assets/img/icons/delete.svg' alt='Hapus' />
                                      </a>";
                            }
                            
                            echo "</td></tr>";
                        }
                    } else {
                        echo "<tr><td colspan='6' class='text-center'>Tidak ada data barang kasir</td></tr>";
                    }
                    ?>

                    </tbody>
                </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script src="/ayula-store/bootstrap/assets/js/jquery-3.6.0.min.js"></script>
  <script src="/ayula-store/bootstrap/assets/js/feather.min.js"></script>
  <script src="/ayula-store/bootstrap/assets/js/jquery.slimscroll.min.js"></script>
  <script src="/ayula-store/bootstrap/assets/js/jquery.dataTables.min.js"></script>
  <script src="/ayula-store/bootstrap/assets/js/dataTables.bootstrap4.min.js"></script>
  <script src="/ayula-store/bootstrap/assets/js/bootstrap.bundle.min.js"></script>
  <script src="/ayula-store/bootstrap/assets/plugins/select2/js/select2.min.js"></script>
  <script src="/ayula-store/bootstrap/assets/plugins/sweetalert/sweetalert2.all.min.js"></script>
  <script src="/ayula-store/bootstrap/assets/plugins/sweetalert/sweetalerts.min.js"></script>
  <script src="/ayula-store/bootstrap/assets/js/script.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <script>
// Function to confirm product deletion
function confirmDelete(id) {
    Swal.fire({
        title: "Apakah Anda yakin?",
        text: "Data yang dihapus tidak bisa dikembalikan!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#d33",
        cancelButtonColor: "#3085d6",
        confirmButtonText: "Ya, hapus!",
        cancelButtonText: "Batal"
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = "/ayula-store/views/barang-kasir/?delete_id=" + id;
        }
    });
}

// Check for success/failure message
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.has('success')) {
    let success = urlParams.get('success');
    if (success == '1') {
        Swal.fire({
            icon: 'success',
            title: 'Berhasil!',
            text: 'Barang kasir berhasil dihapus.',
            showConfirmButton: false,
            timer: 2000
        });
    } else {
        Swal.fire({
            icon: 'error',
            title: 'Gagal!',
            text: 'Barang kasir gagal dihapus.',
            showConfirmButton: true
        });
    }
    // Remove parameter from URL
    window.history.replaceState({}, document.title, window.location.pathname);
}

// Check for edit success message
if (urlParams.has('edit_success')) {
    Swal.fire({
        icon: 'success',
        title: 'Berhasil!',
        text: 'Barang kasir berhasil diperbarui.',
        showConfirmButton: false,
        timer: 2000
    });
    // Remove parameter from URL
    window.history.replaceState({}, document.title, window.location.pathname);
}

// Check for error message
if (urlParams.has('error')) {
    let errorMsg = urlParams.get('error');
    Swal.fire({
        icon: 'error',
        title: 'Oops...',
        text: errorMsg,
        showConfirmButton: true
    });
    // Remove parameter from URL
    window.history.replaceState({}, document.title, window.location.pathname);
}
</script>
</body>

</html>