<?php 

function alt_name_table() {
    global $wpdb;

    return $wpdb->prefix . 'alt_queue_car_images';
}

function alt_get_queue_car_images() {
    global $wpdb;
        
    $queue = $wpdb->get_results("SELECT * FROM " . alt_name_table() . " ORDER BY id LIMIT 1");
    
    $first = reset($queue);
    return [
        $first->id,
        $first->post_id,
        unserialize($first->images),
        $first->meta_key
    ];
}

function alt_count_queue_car_images() {
    global $wpdb;
    
    $count = $wpdb->get_var("SELECT COUNT(*) FROM " . alt_name_table());

    return intval($count);
}

function alt_insert_queue_car_images($post_id, $images, $meta_key = null) {
    global $wpdb;

    $checkTable = alt_check_table_queue_car_images();

    if (!$checkTable && count($images) == 0) {
        return false;
    }


    try {
        $data = [];
        $data['post_id'] = $post_id;
        $data['images'] = serialize($images);
        $data['meta_key'] = $meta_key;
        $data['created_at'] = date("Y-m-d H:i:s");

        $wpdb->insert( alt_name_table(), $data );

        return true;
    } catch (\Throwable $th) {
        error_log($th->getMessage());
    }
    
}

function alt_delete_queue_car_images($post_id) {
    global $wpdb;

    try {
        if ( $post_id > 0 ) {
            $wpdb->delete( alt_name_table(), [ 'id' => $post_id ] );
        }

        return true;
    } catch (\Throwable $th) {
        error_log($th->getMessage());
    }
}

function alt_check_table_queue_car_images(){
    global $wpdb;

    $tablename = alt_name_table();

    if ( $wpdb->get_var( "SHOW TABLES LIKE '$tablename'" ) == $tablename ){
        //se a tabela existir, verificamos se todas as novas colunas existem também
        //senão, adicionamos elas.
        alt_list_columns();
        return true;
    }
        
    //se a tabela não existir, iremos criar
    $existTable =  alt_create_table_queue_car_images();
    
    if ($existTable) {
        return true;
    }
}

function alt_create_table_queue_car_images() {
    $tablename = alt_name_table();

    try {
        $sql = "CREATE TABLE `$tablename` (
            `id` int(10) primary key NOT NULL AUTO_INCREMENT,
            `post_id` varchar(100) NOT NULL,
            `images` text,
            `meta_key` varchar(100) NULL,
            `created_at` datetime
            );";
        
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        
        dbDelta( $sql );
        return true;
    } catch (\Throwable $th) {
        error_log($th->getMessage());
    }
}

function alt_update_column($item){
    global $wpdb;
    
    $table = alt_name_table();
    $colunm = $item["colunm"];
    $parameters = $item["parameters"];
    try {
        $existing_column = $wpdb->get_col("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = '$table' AND column_name = '$colunm'");
        if ($existing_column[0] == 0) {
            $wpdb->query("ALTER TABLE $table ADD COLUMN ".$colunm." ".$parameters."");
        }
        
    } catch (\Throwable $th) {
        error_log($th->getMessage());
    }
}
//adicione aqui todas as novas colunas.
function alt_list_columns(){
    $list = array(['colunm'=>'meta_key', 'parameters'=>'VARCHAR(100) NULL']);
    foreach ($list as $item) {
        alt_update_column($item);
    }
}

