<?php
$host = "localhost";
$username = "kasirmek_kasir";
$password = "*d3l]CQVf$(s#)~e";
$dbname = "kasirmek_kasir";

$conn = mysqli_connect($host, $username, $password, $dbname);
if (!$conn){
        die("Connection Failed:".mysqli_connect_error());
    }
    
date_default_timezone_set('Asia/Jakarta');   
error_reporting(0);

// Helper functions
function ribuan($nilai){
    return number_format($nilai, 0, ',', '.');
}

function get_user_role() {
    if (isset($_SESSION['role'])) {
        return $_SESSION['role'];
    }
    return null;
}

function is_admin() {
    return get_user_role() === 'admin';
}

function is_kasir() {
    return get_user_role() === 'kasir';
}

function check_user_access($required_role = null) {
    // Check if user is logged in
    if (!isset($_SESSION['status']) || $_SESSION['status'] != 'login') {
        header('Location: login.php');
        exit();
    }
    
    // If a specific role is required, check if user has that role
    if ($required_role) {
        $user_role = get_user_role();
        if ($required_role === 'admin' && $user_role !== 'admin') {
            header('Location: index.php');
            exit();
        } elseif ($user_role !== $required_role && $user_role !== 'admin') {
            // Admin can access pages for other roles too
            header('Location: index.php');
            exit();
        }
    }
}

function generate_invoice_number() {
    global $conn;
    $bikin_nota = mysqli_query($conn, "SELECT max(no_nota) as kodeTerbesar11 FROM laporan");
    $datanya = mysqli_fetch_array($bikin_nota);
    $kodenota = $datanya['kodeTerbesar11'];
    $urutan = (int) substr($kodenota, 9, 3);
    $urutan++;
    $tgl = date("jnyGi");
    $huruf = "AD";
    $kodeCart = $huruf . $tgl . sprintf("%03s", $urutan);
    return $kodeCart;
}

function get_pelanggan_umum_id() {
    global $conn;
    $query = mysqli_query($conn, "SELECT idpelanggan FROM pelanggan WHERE nama_pelanggan = 'UMUM' LIMIT 1");
    if ($row = mysqli_fetch_assoc($query)) {
        return $row['idpelanggan'];
    }
    return 0;
}

function get_produk_by_barcode($barcode) {
    global $conn;
    $query = mysqli_query($conn, "SELECT * FROM produk WHERE kode_produk = '$barcode'");
    return mysqli_fetch_assoc($query);
}

function tambah_produk_manual($nama_produk, $harga_jual) {
    global $conn;
    $kode_produk = 'MANUAL_' . time();
    $harga_modal = $harga_jual * 0.8; // 20% margin
    $insert = mysqli_query($conn, "INSERT INTO produk (idkategori, kode_produk, nama_produk, harga_modal, harga_jual, stock, is_manual) VALUES (1, '$kode_produk', '$nama_produk', $harga_modal, $harga_jual, 9999, 1)");
    
    if ($insert) {
        return mysqli_insert_id($conn);
    }
    return false;
}

?>