<?php
session_start();
include 'koneksi.php';

if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

// Tambah/Edit/Delete karyawan
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
if ($_POST['action'] == 'add') {
    $rfid = $_POST['rfid'];
    $nip = $_POST['nip'];
    $nama = $_POST['nama'];
    $jabatan = $_POST['jabatan'];
    $alamat = $_POST['alamat'];
    $no_telp = $_POST['no_telp'];

    // Cek apakah nama atau NIP sudah digunakan
    $cek = mysqli_query($conn, "SELECT * FROM karyawan WHERE nama = '$nama' OR nip = '$nip'");
    if (mysqli_num_rows($cek) > 0) {
        $data = mysqli_fetch_assoc($cek);
        if ($data['nama'] == $nama) {
            $_SESSION['notif'] = "Gagal: Nama '$nama' sudah terdaftar!";
        } elseif ($data['nip'] == $nip) {
            $_SESSION['notif'] = "Gagal: NIP '$nip' sudah digunakan!";
        }
    } else {
        mysqli_query($conn, "INSERT INTO karyawan (rfid, nip, nama, jabatan, alamat, no_telp)
                             VALUES ('$rfid', '$nip', '$nama', '$jabatan', '$alamat', '$no_telp')");
        mysqli_query($conn, "DELETE FROM log_rfid");
        $_SESSION['notif'] = "Data karyawan berhasil ditambahkan!";
    }
}


if ($_POST['action'] == 'edit') {
    $id = $_POST['id'];
    $rfid = $_POST['rfid'];
    $nip = $_POST['nip'];
    $nama = $_POST['nama'];
    $jabatan = $_POST['jabatan'];
    $alamat = $_POST['alamat'];
    $no_telp = $_POST['no_telp'];

    // Cek apakah nama atau NIP sudah digunakan oleh karyawan lain
    $cek = mysqli_query($conn, "SELECT * FROM karyawan WHERE (nama = '$nama' OR nip = '$nip') AND id != $id");
    if (mysqli_num_rows($cek) > 0) {
        $data = mysqli_fetch_assoc($cek);
        if ($data['nama'] == $nama) {
            $_SESSION['notif'] = "Gagal: Nama '$nama' sudah dipakai oleh karyawan lain!";
        } elseif ($data['nip'] == $nip) {
            $_SESSION['notif'] = "Gagal: NIP '$nip' sudah dipakai oleh karyawan lain!";
        }
    } else {
        mysqli_query($conn, "UPDATE karyawan SET 
            rfid='$rfid', nip='$nip', nama='$nama', jabatan='$jabatan',
            alamat='$alamat', no_telp='$no_telp' WHERE id=$id");

        $_SESSION['notif'] = "Data karyawan berhasil diperbarui!";
    }
}



    if ($_POST['action'] == 'delete') {
        $id = $_POST['id'];
        mysqli_query($conn, "DELETE FROM karyawan WHERE id=$id");
        $_SESSION['notif'] = "Data karyawan berhasil dihapus!";
    }

    header("Location: karyawan.php");
    exit();
}

$result = mysqli_query($conn, "SELECT * FROM karyawan");
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Data Karyawan</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        body {
            min-height: 100vh;
            display: flex;
            font-family: 'Poppins', sans-serif;
            background-color: #f4f6f9;
        }
        .sidebar {
            width: 250px;
            background-color: #1f2d3d;
            color: white;
            display: flex;
            flex-direction: column;
            padding-top: 20px;
        }
        .sidebar a {
            color: #cfd8dc;
            text-decoration: none;
            display: flex;
            align-items: center;
            padding: 12px 20px;
        }
        .sidebar a:hover, .sidebar a.active {
            background-color: #273746;
            color: white;
        }
        .content {
            flex-grow: 1;
            padding: 30px;
        }
        .table thead {
            background-color: #1f2d3d;
            color: white;
        }
    </style>
</head>
<body>

    <div class="sidebar">
        <h4 class="text-center text-white mb-4">ABSENSI RFID</h4>
<a href="index.php" ><i class="bi bi-house-door-fill"></i> Beranda</a>
<a href="karyawan.php"class="active"><i class="bi bi-people-fill"></i> Data Karyawan</a>
        <a href="absensi.php"><i class="bi bi-clock-fill"></i> Absensi</a>
        <a href="rekap.php"><i class="bi bi-card-checklist"></i> Rekap Absensi</a>
          <a href="atur_jam.php"><i class="bi bi-clock-history"></i> Set Jam Masuk / Pulang</a> <!-- Tambahan tab baru -->
        <div class="mt-auto">
            <hr class="bg-secondary">
            <a href="logout.php"><i class="bi bi-box-arrow-right"></i> Logout</a>
        </div>
    </div>
<div class="content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3>Data Karyawan</h3>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalTambah">
            <i class="bi bi-plus-circle"></i> Tambah Karyawan
        </button>
    </div>

<?php if (isset($_SESSION['notif'])): ?>
    <div class="alert <?= strpos($_SESSION['notif'], 'Gagal') !== false ? 'alert-danger' : 'alert-success' ?>">
        <?= $_SESSION['notif']; unset($_SESSION['notif']); ?>
    </div>
<?php endif; ?>


    <table class="table table-bordered table-hover">
        <thead>
        <tr>
            <th>No</th>
            <th>RFID</th>
            <th>NIP</th>
            <th>Nama</th>
            <th>Jabatan</th>
            <th>Alamat</th>
            <th>No. Telp</th>
            <th>Aksi</th>
        </tr>
        </thead>
        <tbody>
        <?php $no = 1; while ($row = mysqli_fetch_assoc($result)): ?>
            <tr>
                <td><?= $no++ ?></td>
                <td><?= $row['rfid'] ?></td>
                <td><?= $row['nip'] ?></td>
                <td><?= $row['nama'] ?></td>
                <td><?= $row['jabatan'] ?></td>
                <td><?= $row['alamat'] ?></td>
                <td><?= $row['no_telp'] ?></td>
                <td>
                    <button class="btn btn-sm btn-warning"
                            data-bs-toggle="modal" data-bs-target="#modalEdit"
                            data-id="<?= $row['id'] ?>"
                            data-rfid="<?= $row['rfid'] ?>"
                            data-nip="<?= $row['nip'] ?>"
                            data-nama="<?= $row['nama'] ?>"
                            data-jabatan="<?= $row['jabatan'] ?>"
                            data-alamat="<?= $row['alamat'] ?>"
                            data-no_telp="<?= $row['no_telp'] ?>">
                        <i class="bi bi-pencil-fill"></i>
                    </button>
                    <button class="btn btn-sm btn-danger"
                            data-bs-toggle="modal" data-bs-target="#modalHapus"
                            data-id="<?= $row['id'] ?>" data-nama="<?= $row['nama'] ?>">
                        <i class="bi bi-trash-fill"></i>
                    </button>
                </td>
            </tr>
        <?php endwhile; ?>
        </tbody>
    </table>
</div>

<!-- Modal Tambah -->
<div class="modal fade" id="modalTambah" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="karyawan.php" method="POST" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Tambah Karyawan</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label>RFID (Hanya Scan)</label>
                    <input type="text" class="form-control" name="rfid" id="rfidInput" readonly required
                           style="background-color: #e9ecef; cursor: not-allowed;">
                </div>
                <div class="mb-3"><label>NIP</label><input type="text" class="form-control" name="nip" required></div>
                <div class="mb-3"><label>Nama</label><input type="text" class="form-control" name="nama" required></div>
                <div class="mb-3"><label>Jabatan</label><input type="text" class="form-control" name="jabatan" required></div>
                <div class="mb-3"><label>Alamat</label><input type="text" class="form-control" name="alamat" required></div>
                <div class="mb-3"><label>No. Telp</label><input type="text" class="form-control" name="no_telp" required></div>
            </div>
            <div class="modal-footer">
                <input type="hidden" name="action" value="add">
                <button type="submit" class="btn btn-primary">Simpan</button>
            </div>
        </form>
    </div>
</div>

<!-- Modal Edit -->
<div class="modal fade" id="modalEdit" tabindex="-1">
    <div class="modal-dialog">
        <form action="karyawan.php" method="POST" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Karyawan</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label>RFID</label>
                    <input type="text" class="form-control" name="rfid" id="editRfid" readonly required
                           style="background-color: #e9ecef; cursor: not-allowed;">
                </div>
                <div class="mb-3"><label>NIP</label><input type="text" class="form-control" name="nip" id="editNip" required></div>
                <div class="mb-3"><label>Nama</label><input type="text" class="form-control" name="nama" id="editNama" required></div>
                <div class="mb-3"><label>Jabatan</label><input type="text" class="form-control" name="jabatan" id="editJabatan" required></div>
                <div class="mb-3"><label>Alamat</label><input type="text" class="form-control" name="alamat" id="editAlamat" required></div>
                <div class="mb-3"><label>No. Telp</label><input type="text" class="form-control" name="no_telp" id="editNoTelp" required></div>
            </div>
            <div class="modal-footer">
                <input type="hidden" name="action" value="edit">
                <input type="hidden" name="id" id="editId">
                <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
            </div>
        </form>
    </div>
</div>

<!-- Modal Hapus -->
<div class="modal fade" id="modalHapus" tabindex="-1">
    <div class="modal-dialog">
        <form action="karyawan.php" method="POST" class="modal-content">
            <div class="modal-header"><h5 class="modal-title">Konfirmasi Hapus</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body"><p>Apakah Anda yakin ingin menghapus <strong id="hapusNama"></strong>?</p></div>
            <div class="modal-footer">
                <input type="hidden" name="id" id="hapusId">
                <input type="hidden" name="action" value="delete">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                <button type="submit" class="btn btn-danger">Hapus</button>
            </div>
        </form>
    </div>
</div>

<!-- Script -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    const modalEdit = document.getElementById('modalEdit');
    modalEdit?.addEventListener('show.bs.modal', event => {
        const button = event.relatedTarget;
        document.getElementById('editId').value = button.getAttribute('data-id');
        document.getElementById('editRfid').value = button.getAttribute('data-rfid');
        document.getElementById('editNip').value = button.getAttribute('data-nip');
        document.getElementById('editNama').value = button.getAttribute('data-nama');
        document.getElementById('editJabatan').value = button.getAttribute('data-jabatan');
        document.getElementById('editAlamat').value = button.getAttribute('data-alamat');
        document.getElementById('editNoTelp').value = button.getAttribute('data-no_telp');
    });

    const modalHapus = document.getElementById('modalHapus');
    modalHapus?.addEventListener('show.bs.modal', event => {
        const button = event.relatedTarget;
        document.getElementById('hapusId').value = button.getAttribute('data-id');
        document.getElementById('hapusNama').innerText = button.getAttribute('data-nama');
    });

    // AJAX: Cek RFID terbaru
    setInterval(() => {
        fetch('get_rfid.php')
            .then(res => res.json())
            .then(data => {
                if (data.rfid) {
                    document.getElementById('rfidInput').value = data.rfid;
                }
            });
    }, 2000);
</script>
</body>
</html>
