<?php

if (!function_exists('redirect')) {
    function redirect($url) {
        header("Location: $url");
        exit;
    }
}

if (!function_exists('isLogin')) {
    function isLogin() {
        return isset($_SESSION['login']);
    }
}

if (!function_exists('isAdmin')) {
    function isAdmin() {
        return isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
    }
}

if (!function_exists('isClient')) {
    function isClient() {
        return isset($_SESSION['role']) && $_SESSION['role'] === 'client';
    }
}

if (!function_exists('rupiah')) {
    function rupiah($angka) {
        return "Rp " . number_format($angka, 0, ',', '.');
    }
}

if (!function_exists('setFlash')) {
    function setFlash($type, $message) {
        $_SESSION['flash'] = [
            'type' => $type,
            'message' => $message
        ];
    }
}

if (!function_exists('showFlash')) {
    function showFlash() {
        if (isset($_SESSION['flash'])) {
            $type = $_SESSION['flash']['type'];
            $message = $_SESSION['flash']['message'];

            echo "<div class='alert alert-$type alert-dismissible fade show' role='alert'>
                    $message
                    <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                  </div>";

            unset($_SESSION['flash']);
        }
    }
}

if (!function_exists('createDefaultUsers')) {
    function createDefaultUsers($conn) {
        $check = mysqli_query($conn, "SELECT COUNT(*) as total FROM users");
        $row = mysqli_fetch_assoc($check);

        if ($row && $row['total'] == 0) {
            $adminPass = password_hash("admin123", PASSWORD_DEFAULT);
            $clientPass = password_hash("client123", PASSWORD_DEFAULT);

            mysqli_query($conn, "INSERT INTO users (nama, username, password, role, saldo) VALUES
                ('Administrator', 'admin', '$adminPass', 'admin', 0),
                ('Client Demo', 'client', '$clientPass', 'client', 500000)
            ");
        }
    }
}
?>