<?php 
require_once 'includes/auth.php';
require_once 'includes/config.php';
checkRole(['superadmin']); // Hanya superadmin yang bisa akses halaman users

// Ambil data superadmin yang sedang login
try {
    $stmt = $pdo->prepare("SELECT * FROM superadmin WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $superadmin = $stmt->fetch();
} catch(PDOException $e) {
    error_log("Error fetching superadmin: " . $e->getMessage());
}

// Proses update superadmin
if(isset($_POST['update'])) {
    if (!isset($_POST['csrf_token']) || !verifyCSRFToken($_POST['csrf_token'])) {
        $_SESSION['error'] = "Token keamanan tidak valid!";
        header("Location: users.php");
        exit();
    }

    $username = sanitize_input($_POST['username']);
    $password = $_POST['password'];
    $password_confirmation = $_POST['password_confirmation'];

    try {
        // Cek apakah username sudah digunakan
        $stmt = $pdo->prepare("SELECT id FROM superadmin WHERE username = ? AND id != ?");
        $stmt->execute([$username, $_SESSION['user_id']]);
        if($stmt->fetch()) {
            $_SESSION['error'] = "Username sudah digunakan!";
            header("Location: users.php");
            exit();
        }

        if($password) {
            if($password !== $password_confirmation) {
                $_SESSION['error'] = "Konfirmasi password tidak sesuai!";
                header("Location: users.php");
                exit();
            }
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE superadmin SET username = ?, password = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$username, $hashed_password, $_SESSION['user_id']]);
        } else {
            $stmt = $pdo->prepare("UPDATE superadmin SET username = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$username, $_SESSION['user_id']]);
        }

        $_SESSION['success'] = "Profil berhasil diupdate!";
        header("Location: users.php");
        exit();

    } catch(PDOException $e) {
        error_log("Error updating superadmin: " . $e->getMessage());
        $_SESSION['error'] = "Terjadi kesalahan saat mengupdate profil!";
        header("Location: users.php");
        exit();
    }
}

// Ambil data supervisor
try {
    $stmt = $pdo->prepare("SELECT * FROM supervisor WHERE deleted_at IS NULL ORDER BY id ASC");
    $stmt->execute();
    $supervisors = $stmt->fetchAll();
} catch(PDOException $e) {
    error_log("Error fetching supervisors: " . $e->getMessage());
}

// Proses tambah supervisor
if(isset($_POST['add_supervisor'])) {
    if (!isset($_POST['csrf_token']) || !verifyCSRFToken($_POST['csrf_token'])) {
        $_SESSION['error'] = "Token keamanan tidak valid!";
        header("Location: users.php");
        exit();
    }

    $username = sanitize_input($_POST['username']);
    $password = $_POST['password'];
    $password_confirmation = $_POST['password_confirmation'];
    $nama_lengkap = sanitize_input($_POST['nama_lengkap']);
    $email = sanitize_input($_POST['email']);

    try {
        // Cek apakah username sudah digunakan
        $stmt = $pdo->prepare("SELECT id FROM supervisor WHERE username = ?");
        $stmt->execute([$username]);
        if($stmt->fetch()) {
            $_SESSION['error'] = "Username sudah digunakan!";
            header("Location: users.php");
            exit();
        }

        // Cek apakah email sudah digunakan
        $stmt = $pdo->prepare("SELECT id FROM supervisor WHERE email = ?");
        $stmt->execute([$email]);
        if($stmt->fetch()) {
            $_SESSION['error'] = "Email sudah digunakan!";
            header("Location: users.php");
            exit();
        }

        // Validasi password
        if($password !== $password_confirmation) {
            $_SESSION['error'] = "Konfirmasi password tidak sesuai!";
            header("Location: users.php");
            exit();
        }

        // Insert supervisor baru
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("INSERT INTO supervisor (username, password, nama_lengkap, email, created_at) VALUES (?, ?, ?, ?, NOW())");
        $stmt->execute([$username, $hashed_password, $nama_lengkap, $email]);

        $_SESSION['success'] = "Supervisor berhasil ditambahkan!";
        header("Location: users.php");
        exit();

    } catch(PDOException $e) {
        error_log("Error adding supervisor: " . $e->getMessage());
        $_SESSION['error'] = "Terjadi kesalahan saat menambahkan supervisor!";
        header("Location: users.php");
        exit();
    }
}

// Proses edit supervisor
if(isset($_POST['edit_supervisor'])) {
    if (!isset($_POST['csrf_token']) || !verifyCSRFToken($_POST['csrf_token'])) {
        $_SESSION['error'] = "Token keamanan tidak valid!";
        header("Location: users.php");
        exit();
    }

    $supervisor_id = $_POST['supervisor_id'];
    $username = sanitize_input($_POST['username']);
    $nama_lengkap = sanitize_input($_POST['nama_lengkap']);
    $email = sanitize_input($_POST['email']);
    $password = $_POST['password'];
    $password_confirmation = $_POST['password_confirmation'];

    try {
        // Cek apakah username sudah digunakan oleh supervisor lain
        $stmt = $pdo->prepare("SELECT id FROM supervisor WHERE username = ? AND id != ?");
        $stmt->execute([$username, $supervisor_id]);
        if($stmt->fetch()) {
            $_SESSION['error'] = "Username sudah digunakan!";
            header("Location: users.php");
            exit();
        }

        // Cek apakah email sudah digunakan oleh supervisor lain
        $stmt = $pdo->prepare("SELECT id FROM supervisor WHERE email = ? AND id != ?");
        $stmt->execute([$email, $supervisor_id]);
        if($stmt->fetch()) {
            $_SESSION['error'] = "Email sudah digunakan!";
            header("Location: users.php");
            exit();
        }

        if($password) {
            if($password !== $password_confirmation) {
                $_SESSION['error'] = "Konfirmasi password tidak sesuai!";
                header("Location: users.php");
                exit();
            }
            // Update dengan password baru
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE supervisor SET username = ?, nama_lengkap = ?, email = ?, password = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$username, $nama_lengkap, $email, $hashed_password, $supervisor_id]);
        } else {
            // Update tanpa mengubah password
            $stmt = $pdo->prepare("UPDATE supervisor SET username = ?, nama_lengkap = ?, email = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$username, $nama_lengkap, $email, $supervisor_id]);
        }

        $_SESSION['success'] = "Data supervisor berhasil diupdate!";
        header("Location: users.php");
        exit();

    } catch(PDOException $e) {
        error_log("Error updating supervisor: " . $e->getMessage());
        $_SESSION['error'] = "Terjadi kesalahan saat mengupdate supervisor!";
        header("Location: users.php");
        exit();
    }
}

// Proses delete supervisor
if(isset($_POST['delete_supervisor'])) {
    if (!isset($_POST['csrf_token']) || !verifyCSRFToken($_POST['csrf_token'])) {
        $_SESSION['error'] = "Token keamanan tidak valid!";
        header("Location: users.php");
        exit();
    }

    $supervisor_id = $_POST['supervisor_id'];

    try {
        // Soft delete dengan mengupdate deleted_at
        $stmt = $pdo->prepare("UPDATE supervisor SET deleted_at = NOW() WHERE id = ?");
        $stmt->execute([$supervisor_id]);

        $_SESSION['success'] = "Supervisor berhasil dihapus!";
        header("Location: users.php");
        exit();

    } catch(PDOException $e) {
        error_log("Error deleting supervisor: " . $e->getMessage());
        $_SESSION['error'] = "Terjadi kesalahan saat menghapus supervisor!";
        header("Location: users.php");
        exit();
    }
}

include 'includes/header.php'; 
include 'includes/sidebar.php';

// Ambil pesan error/success dari session
$error = isset($_SESSION['error']) ? $_SESSION['error'] : null;
$success = isset($_SESSION['success']) ? $_SESSION['success'] : null;
unset($_SESSION['error'], $_SESSION['success']);
?>

<div class="content" id="content">
    <div class="container-fluid">
        <h1 class="h3 mb-4">Users</h1>
        
        <?php if($error): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $error; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if($success): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo $success; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <!-- Superadmin Edit Card -->
        <div class="card mb-4 mt-4">
            <div class="card-header">
                <h5 class="mb-0">Superadmin Edit</h5>
            </div>
            <div class="card-body mt-4 mb-4">
                <form method="POST" action="">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                    <div class="mb-3">
                        <input type="text" class="form-control" id="username" name="username" 
                               value="<?php echo htmlspecialchars($superadmin['username']); ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <input type="password" class="form-control" id="password" name="password" 
                               placeholder="Enter new password">
                        <small class="text-muted">Leave blank if you don't want to change the password</small>
                    </div>

                    <div class="mb-3">
                        <input type="password" class="form-control" id="password_confirmation" 
                               name="password_confirmation" placeholder="Confirm new password">
                    </div>

                        <button type="submit" name="update" class="btn btn-primary">
                            <i class="fas fa-save me-2"></i>UPDATE
                        </button>
                </form>
            </div>
        </div>

        <!-- Supervisor Table -->
        <h5 class="mb-3">Supervisor</h5>
        <div class="d-flex justify-content-between align-items-center mb-3">
            <div class="input-group input-group-sm" style="width: 250px;">
                <span class="input-group-text bg-light">
                    <i class="fas fa-search text-primary"></i>
                </span>
                <input type="text" class="form-control" id="searchInput" placeholder="Search username...">
            </div>
            <button class="btn btn-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addSupervisorModal">
                <i class="fas fa-plus me-1"></i>Add Supervisor
            </button>
        </div>

        <div class="card">
            <div class="card-body">
                <table class="table">
                    <thead>
                        <tr>
                            <th width="10%">No.</th>
                            <th>Username</th>
                            <th>Nama Lengkap</th>
                            <th>Email</th>
                            <th width="15%" class="text-center">Action</th>
                        </tr>
                    </thead>
                    <tbody id="supervisorTable">
                        <?php 
                        $no = 1;
                        foreach($supervisors as $supervisor): 
                        ?>
                        <tr>
                            <td><?php echo $no++; ?></td>
                            <td><?php echo htmlspecialchars($supervisor['username']); ?></td>
                            <td><?php echo htmlspecialchars($supervisor['nama_lengkap']); ?></td>
                            <td><?php echo htmlspecialchars($supervisor['email']); ?></td>
                            <td class="text-center">
                                <div class="btn-group" role="group">
                                    <button class="btn btn-sm btn-warning" data-bs-toggle="modal" 
                                            data-bs-target="#editSupervisorModal" 
                                            data-id="<?php echo $supervisor['id']; ?>"
                                            data-username="<?php echo htmlspecialchars($supervisor['username']); ?>"
                                            data-nama="<?php echo htmlspecialchars($supervisor['nama_lengkap']); ?>"
                                            data-email="<?php echo htmlspecialchars($supervisor['email']); ?>">
                                    <i class="fas fa-edit"></i>
                                </button>
                                    <button class="btn btn-sm btn-danger" data-bs-toggle="modal" 
                                            data-bs-target="#deleteSupervisorModal"
                                            data-id="<?php echo $supervisor['id']; ?>">
                                    <i class="fas fa-trash"></i>
                                </button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add Supervisor Modal -->
<div class="modal fade" id="addSupervisorModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Supervisor</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="">
                <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
            <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Username</label>
                        <input type="text" class="form-control" name="username" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Nama Lengkap</label>
                        <input type="text" class="form-control" name="nama_lengkap" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" class="form-control" name="email" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Password</label>
                        <input type="password" class="form-control" name="password" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Confirm Password</label>
                        <input type="password" class="form-control" name="password_confirmation" required>
                    </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="add_supervisor" class="btn btn-primary btn-sm">Add</button>
            </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Supervisor Modal -->
<div class="modal fade" id="editSupervisorModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Supervisor</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="">
                <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                <input type="hidden" name="supervisor_id" id="edit_supervisor_id">
            <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Username</label>
                        <input type="text" class="form-control" name="username" id="edit_username" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Nama Lengkap</label>
                        <input type="text" class="form-control" name="nama_lengkap" id="edit_nama_lengkap" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" class="form-control" name="email" id="edit_email" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">New Password</label>
                        <input type="password" class="form-control" name="password" placeholder="Enter new password">
                        <small class="text-muted">Leave blank if you don't want to change the password</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Confirm New Password</label>
                        <input type="password" class="form-control" name="password_confirmation" placeholder="Confirm new password">
                    </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="edit_supervisor" class="btn btn-primary btn-sm">Update</button>
            </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Supervisor Modal -->
<div class="modal fade" id="deleteSupervisorModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Delete Supervisor</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="">
                <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                <input type="hidden" name="supervisor_id" id="delete_supervisor_id">
            <div class="modal-body">
                <p>Are you sure you want to delete this supervisor account?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="delete_supervisor" class="btn btn-danger btn-sm">Delete</button>
            </div>
            </form>
        </div>
    </div>
</div>

<script>
document.getElementById('searchInput').addEventListener('keyup', function() {
    let searchQuery = this.value.toLowerCase();
    let tableBody = document.getElementById('supervisorTable');
    let rows = tableBody.getElementsByTagName('tr');

    for (let row of rows) {
        let username = row.getElementsByTagName('td')[1].textContent.toLowerCase();
        let nama = row.getElementsByTagName('td')[2].textContent.toLowerCase();
        let email = row.getElementsByTagName('td')[3].textContent.toLowerCase();
        
        if (username.includes(searchQuery) || 
            nama.includes(searchQuery) || 
            email.includes(searchQuery)) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    }
});

// Script untuk modal edit
document.querySelectorAll('[data-bs-target="#editSupervisorModal"]').forEach(button => {
    button.addEventListener('click', function() {
        const id = this.getAttribute('data-id');
        const username = this.getAttribute('data-username');
        const nama = this.getAttribute('data-nama');
        const email = this.getAttribute('data-email');

        document.getElementById('edit_supervisor_id').value = id;
        document.getElementById('edit_username').value = username;
        document.getElementById('edit_nama_lengkap').value = nama;
        document.getElementById('edit_email').value = email;
    });
});

// Script untuk modal delete
document.querySelectorAll('[data-bs-target="#deleteSupervisorModal"]').forEach(button => {
    button.addEventListener('click', function() {
        const id = this.getAttribute('data-id');
        document.getElementById('delete_supervisor_id').value = id;
    });
});
</script>

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