<?php


$koneksi = mysqli_connect("localhost", "root", "", "kasir_warkop");


// Funtion Register

function register_akun()

{

    global $koneksi;



    $username = htmlspecialchars($_POST["username"]);

    $password = md5(htmlspecialchars($_POST["password"]));

    $konfirmasi_password = md5(htmlspecialchars($_POST["konfirmasi-password"]));



    $cek_username = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT * FROM `user` WHERE username = '$username'"));



    if ($cek_username != null) {

        echo "<script>

            alert('Username sudah ada!');

        </script>";

        return -1;
    } else if ($password != $konfirmasi_password) {

        echo "<script>

            alert('Password Tidak Sesuai!');

        </script>";

        return -1;
    }



    mysqli_query($koneksi, "INSERT INTO `user`

                            VALUES ('', '$username', '$password')

    ");

    return mysqli_affected_rows($koneksi);
}



// Function Login

function login_akun()

{

    global $koneksi;



    $username = htmlspecialchars($_POST["username"]);

    $password = md5(htmlspecialchars($_POST["password"]));



    $cek_akun_admin = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT * FROM `admin` 

                                                           WHERE username = '$username' AND 

                                                                `password` = '$password'

    "));

    $cek_akun_user = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT * FROM `user` 

                                                           WHERE username = '$username' AND 

                                                                `password` = '$password'

    "));



    if ($cek_akun_admin == null && $cek_akun_user == null) return false;

    if ($cek_akun_user != null) {

        $_SESSION["akun-user"] = [

            "username" => $username,

            "password" => $password

        ];
    }
    if ($cek_akun_admin != null) {

        $_SESSION["akun-admin"] = [

            "username" => $username,

            "password" => $password

        ];
    }

    header("Location: index.php");

    exit;
}



// Function Select Data

function ambil_data($query)

{

    global $koneksi;



    $db = [];

    $sql_query = mysqli_query($koneksi, $query);

    while ($q = mysqli_fetch_assoc($sql_query)) {

        array_push($db, $q);
    }

    return $db;
}



function tambah_data_menu()
{
    global $koneksi;

    $nama     = htmlspecialchars($_POST["nama"]);
    $harga    = (int) $_POST["harga"];
    $kategori = htmlspecialchars($_POST["kategori"]);
    $status   = htmlspecialchars($_POST["status"]);
    $gambar   = $_FILES["gambar"]["name"];

    /* ================= ID_MENU DIMULAI DARI 36 ================= */
    $dataId = ambil_data("
        SELECT MAX(id_menu) AS id 
        FROM menu
    ");

    $lastId = (int) ($dataId[0]["id"] ?? 35);
    $id_menu = $lastId + 1; // mulai 36

    /* ================= KODE MENU : menu001 ================= */
    $dataKode = ambil_data("
        SELECT MAX(CAST(SUBSTR(kode_menu, 5) AS UNSIGNED)) AS kode
        FROM menu
    ");

    $lastKode = (int) ($dataKode[0]["kode"] ?? 0);
    $newKode  = $lastKode + 1;

    $kode_menu = "menu" . str_pad($newKode, 3, "0", STR_PAD_LEFT);

    /* ================= CEK GAMBAR ================= */
$format_gambar = ["jpg", "jpeg", "png", "gif"];
$ext = strtolower(pathinfo($gambar, PATHINFO_EXTENSION));

if (!in_array($ext, $format_gambar)) {
    echo "<script>alert('File yang diupload bukan image!');</script>";
    return -1;
}

/* ================= BUAT NAMA FILE GAMBAR DARI NAMA MENU ================= */
// ubah nama menu jadi lowercase, tanpa spasi & karakter aneh
$nama_menu_bersih = strtolower($nama);
$nama_menu_bersih = preg_replace('/[^a-z0-9]/', '_', $nama_menu_bersih);

// contoh hasil: kopi_hitam_1712345678.jpg
$nama_gambar = $nama_menu_bersih . "_" . time() . "." . $ext;

/* ================= UPLOAD GAMBAR ================= */
move_uploaded_file(
    $_FILES["gambar"]["tmp_name"],
    "src/img/" . $nama_gambar
);


    /* ================= INSERT DATA ================= */
    mysqli_query($koneksi, "
        INSERT INTO menu (id_menu, kode_menu, nama, harga, gambar, kategori, status)
        VALUES (
            $id_menu,
            '$kode_menu',
            '$nama',
            $harga,
            '$nama_gambar',
            '$kategori',
            '$status'
        )
    ");

    return mysqli_affected_rows($koneksi);
}




// Function Edit Data Menu

function edit_data_menu()

{

    global $koneksi;



    $id_menu = $_POST["id_menu"];

    $nama = htmlspecialchars($_POST["nama"]);

    $harga = (int) htmlspecialchars($_POST["harga"]);

    $gambar = htmlspecialchars($_FILES["gambar"]["name"]);

    $kategori = htmlspecialchars($_POST["kategori"]);

    $status = htmlspecialchars($_POST["status"]);

    $kode_menu = htmlspecialchars($_POST["kode_menu"]);



    // cek format gambar

    $format_gambar = ["jpg", "jpeg", "png", "gif"];

    $cek_gambar = explode(".", $gambar);

    $cek_gambar = strtolower(end($cek_gambar));

    if (!in_array($cek_gambar, $format_gambar) && strlen($gambar) != 0) {

        echo "<script>

            alert('File yang diupload bukan merupakan image!');

        </script>";

        return -1;
    }



    // cek jika admin mengupload gambar yang baru

    $gambar_lama = $_POST["gambar-lama"];



    if (strlen($gambar) == 0) {

        $gambar = $gambar_lama;
    } else if ($gambar != $gambar_lama && strlen($gambar) != 0) {

        move_uploaded_file($_FILES["gambar"]["tmp_name"], "src/img/$gambar");

        unlink("src/img/$gambar_lama");
    }



    // eksekusi query update

    mysqli_query($koneksi, "UPDATE menu

                            SET kode_menu = '$kode_menu',

                                nama = '$nama',

                                harga = $harga,

                                gambar = '$gambar',

                                kategori = '$kategori',

                                `status` = '$status'

                            WHERE id_menu = $id_menu

    ");

    return mysqli_affected_rows($koneksi);
}


// =============================
// HAPUS DATA PESANAN & TRANSAKSI
// =============================
function hapus_data_pesanan()
{
    global $koneksi;

    if (!isset($_GET["kode_pesanan"])) {
        return -1;
    }

    $kode_pesanan = $_GET["kode_pesanan"];

    // HAPUS DETAIL PESANAN
    mysqli_query($koneksi, "
        DELETE FROM pesanan 
        WHERE kode_pesanan = '$kode_pesanan'
    ");

    // HAPUS TRANSAKSI
    mysqli_query($koneksi, "
        DELETE FROM transaksi 
        WHERE kode_pesanan = '$kode_pesanan'
    ");

    return mysqli_affected_rows($koneksi);
}

// Function Hapus Data Menu

function hapus_data_menu()

{

    global $koneksi;



    $id_menu = $_GET["id_menu"];



    // hapus file gambar

    $file_gambar = ambil_data("SELECT * FROM menu WHERE id_menu = $id_menu")[0]["gambar"];

    unlink("src/img/$file_gambar");



    // eksekusi query delete

    mysqli_query($koneksi, "DELETE FROM menu

                            WHERE id_menu = $id_menu

    ");

    return mysqli_affected_rows($koneksi);
}



// Tambah Data Pesanan & Transaksi
function tambah_data_pesanan()
{
    global $koneksi;

    // Nama Pelanggan
    $pelanggan = htmlspecialchars($_POST["pelanggan"]);

    // Generate Kode Pesanan
    $kode_pesanan = uniqid();

    // Ambil jumlah menu
    $max_menu = count(ambil_data("SELECT * FROM menu"));

    $list_pesanan = [];

    for ($i = 1; $i <= $max_menu; $i++) {
        if (isset($_POST["qty$i"]) && (int)$_POST["qty$i"] > 0) {
            $list_pesanan[] = [
                "kode_menu" => $_POST["kode_menu$i"],
                "qty" => (int) $_POST["qty$i"]
            ];
        }
    }

    // Cek jika tidak ada pesanan
    if (count($list_pesanan) == 0) {
        echo "<script>alert('Anda belum memesan menu!');</script>";
        return -1;
    }

    // =============================
    // INSERT KE TABEL PESANAN
    // =============================
    foreach ($list_pesanan as $lp) {
        $kode_menu = $lp["kode_menu"];
        $qty = $lp["qty"];

        mysqli_query($koneksi, "
            INSERT INTO pesanan 
            (kode_pesanan, kode_menu, qty)
            VALUES 
            ('$kode_pesanan', '$kode_menu', $qty)
        ");
    }

    

    // =============================
    // INSERT KE TABEL TRANSAKSI
    // =============================
    mysqli_query($koneksi, "
        INSERT INTO transaksi 
        (kode_pesanan, nama_pelanggan, waktu, status)
        VALUES 
        ('$kode_pesanan', '$pelanggan', NOW(), 'BELUM LUNAS')
    ");

    return mysqli_affected_rows($koneksi);

}
