<?php
    // if($conn){
    //     echo "True";
    // }
    function check_duplicate($table_name, $data, $conn){
        $check_duplicate_sql = "SELECT * FROM $table_name WHERE ";
        foreach ($data as $key => $value) {
            $check_duplicate_sql .= "$key = '$value' AND ";
        }
        $check_duplicate_sql = rtrim($check_duplicate_sql, " AND ");
        $result = mysqli_query($conn, $check_duplicate_sql);
        if (mysqli_num_rows($result) > 0) {
            return false; // data sudah ada di dalam tabel
        }else{
            return true;
        }
    }

    function create($table_name, $data) {
        global $conn;
        $keys = implode(", ", array_keys($data));
        $values = "'" . implode("', '", $data) . "'";

        if(check_duplicate($table_name, $data, $conn)){
            $sql = "INSERT INTO $table_name ($keys) VALUES ($values)";
            if (mysqli_query($conn, $sql)) {
                return true;
            } else {
                return false;
            }
        }
    }

    function read($table_name, $where = "", $sql = "") {
        global $conn;
        $sql = "SELECT * FROM $table_name ORDER BY id DESC $sql";
        if (!empty($where)) {
            $sql .= " WHERE $where";
        }
        $result = mysqli_query($conn, $sql);
        $rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
        return $rows;
    }

    function update($table_name, $data, $where) {
        global $conn;
        $set = "";
        foreach ($data as $key => $value) {
            $set .= "$key = '$value', ";
        }
        $set = rtrim($set, ", ");
        $sql = "UPDATE $table_name SET $set WHERE $where";
        if (mysqli_query($conn, $sql)) {
            return true;
        } else {
            return false;
        }
    }

    function delete($table_name, $where) {
        global $conn;
        $sql = "DELETE FROM $table_name WHERE $where";
        if (mysqli_query($conn, $sql)) {
            return true;
        } else {
            return false;
        }
    }

    function get_jum_table($table){
        global $conn;
        $sql = "SELECT COUNT(*) AS count FROM $table";
        $result = mysqli_query($conn, $sql);

        if ($result) {
            $row = mysqli_fetch_assoc($result);
            return $row['count'];
        } else {
            // Menangani kesalahan jika query gagal
            return false;
        }
    }
    
    // $data = array(
    //     'nim' => '24060118130198',
    //     'nama' => 'Tryo Irtadlo',
    //     'kelas' => 'X TKJ A',
    //     'umur' => 19
    // );

    // delete("king", "nim = 24060118130199");

    // update("king", array("nim" => "24060118130199"), "nim = 24060118130198");

    // $users = read("king");

    // for($i = 0; $i < count($users); $i++){
    //     print_r($users[$i]['nim']);
    //     print_r($users[$i]['nama']);
    //     echo '<br>';
    // }



?>