<?php

add_action('cmb2_init', 'alt_metabox_parceria');


/**
 * Define the metabox and field configurations.
 */
function alt_metabox_parceria()
{
    $prefix = 'alt_';

    /**
     * Initiate the metabox
     */
    $cmb = new_cmb2_box(array(
        'id' => 'field_parceria',
        'title' => 'Parcerias',
        'object_types' => array('parcerias'), // Post type
        'context' => 'normal',
        'priority' => 'high',
        'show_names' => true,
        'show_in_rest' => false,
    ));

    $cmb->add_field(array(
        'name' => 'Selecione a logo da parceria',
        'desc' => 'Selecione o arquivo ou informe a URL.',
        'id' => $prefix . 'parcerias_imagem',
        'type' => 'file',
        // Optional:
        'options' => array(
            'url' => true, // Hide the text input for the url
        ),
        'text' => array(
            'add_upload_file_text' => 'Adicionar arquivo' // Change upload button text. Default: "Add or Upload File"
        ),
        // query_args are passed to wp.media's library query.
        'query_args' => array(
            //'type' => 'application/pdf', // Make library only display PDFs.
            // Or only allow gif, jpg, or png images
            'type' => array(
                'image/gif',
                'image/jpeg',
                'image/png',
            ),
        ),
        'preview_size' => 'thumbnail', // Image size to use when previewing in the admin.
    ));

    $cmb->add_field(array(
        'name' => 'Link da parceria',
        'desc' => 'Insira o link da parceria',
        'id' => $prefix . 'parcerias_link',
        'type' => 'text_url',
        'protocols' => array('http', 'https'),
    ));
    
    $cmb->add_field(array(
        'name' => 'Descrição',
        'desc' => 'Inserir a descrição e o telefone de contato',
        'default' => '',
        'id' => $prefix . 'parcerias_descricao',
        'type' => 'wysiwyg',
    ));
}

function alt_get_parcerias()
{

    $args = array(
        'post_type' => 'parcerias',
        'post_status' => array('publish'),
        'orderBy' => 'date',
        'order' => 'asc',
    );

    $query = new WP_Query($args);
    $arrParcerias = $query->posts;

    $objReturn = new stdClass();
    foreach ($arrParcerias as $parceria) {
        $objReturn->{$parceria->ID} = new stdClass();
        $objReturn->{$parceria->ID}->id = $parceria->ID;
        $objReturn->{$parceria->ID}->title = $parceria->post_title;
        $objReturn->{$parceria->ID}->imagem = get_post_meta($parceria->ID, 'alt_parcerias_imagem', true);
        $objReturn->{$parceria->ID}->descricao = get_post_meta($parceria->ID, 'alt_parcerias_descricao', true);
        $objReturn->{$parceria->ID}->link = get_post_meta($parceria->ID, 'alt_parcerias_link', true);
    }
    wp_reset_query();

    
    if(!$objReturn){
        return new stdClass();
    }

    return $objReturn;
}
