<?php
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}


/**
 * VERIFICAR SE EXISTE ALGUMA MARCA CADASTRADA, SE NÃO, ENTÃO INCLUIR AUTOMATICAMENTE AS MARCAS PADRÕES
 */

function create_database_lead()
{
    // create the custom table
    global $wpdb;


    $table_name = $wpdb->prefix . 'alt_leads';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE IF NOT EXISTS $table_name ( 
  `id` INT NOT NULL AUTO_INCREMENT,
  `permalink` VARCHAR(255),
  `nome` VARCHAR(255),
  `email` VARCHAR(255),
  `telefone` VARCHAR(255),
  `marca` VARCHAR(255),
  `modelo` VARCHAR(255),
  `valor` VARCHAR(255),
  `created_at` VARCHAR(255),
  `mensagem` TEXT,
  PRIMARY KEY (`id`)
) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}


function contactform7_before_send_mail($form_to_DB)
{


    global $wpdb;

    $table_name = $wpdb->prefix . 'alt_leads';

    $form_to_DB = WPCF7_Submission::get_instance();
    if ($form_to_DB)
        $formData = $form_to_DB->get_posted_data();


    $form['permalink'] = $formData['permalink'];
    $form['nome'] = $formData['nome'];
    $form['email'] = $formData['email'];
    $form['telefone'] = $formData['telefone'];
    $form['marca'] = $formData['marca'];
    $form['modelo'] = $formData['modelo'];
    $form['valor'] = $formData['valor'];
    $form['created_at'] = date('Y-m-d H:i:s');
    $form['mensagem'] = $formData['mensagem'];


    $wpdb->insert($table_name, $form, array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'));
    $my_id = $wpdb->insert_id;


}

//remove_all_filters('wpcf7_before_send_mail');
add_action('wpcf7_before_send_mail', 'contactform7_before_send_mail');


/**
 * Criação automatica de dados
 */

add_action('wp_ajax_criar_paginas_default', 'criar_paginas_default');
//add_action('wp_ajax_nopriv_criar_paginas_default','criar_paginas_default');
//do_action('criar_paginas_default');
function criar_paginas_default()
{



    /**
     * Criar páginas
     */
    if (!get_page_by_title('Home')) {
        $home_id = wp_insert_post(
            array(
                'comment_status' => 'close',
                'ping_status' => 'close',
                'post_author' => 1,
                'post_title' => 'Home',
                'post_name' => 'home',
                'post_status' => 'publish',
                'post_content' => '',
                'post_type' => 'page',
                'post_parent' => ''
            )
        );

    };

    if (!get_page_by_title('Estoque')) {
        $estoque_id = wp_insert_post(
            array(
                'comment_status' => 'close',
                'ping_status' => 'close',
                'post_author' => 1,
                'post_title' => 'Estoque',
                'post_name' => 'estoque',
                'post_status' => 'publish',
                'post_content' => '',
                'post_type' => 'page',
                'post_parent' => ''
            )
        );

        if (!metadata_exists('post', $estoque_id, '_wp_page_template')) {
            //add_post_meta($estoque_id, '_wp_page_template', 'page-estoque.php');
            update_post_meta($estoque_id, '_wp_page_template', 'page-estoque.php');
        }
    };

    if (!get_page_by_title('Empresa')) {
        $html_modelo_quem_somos = "<h1>Criar texto para a loja</h1>";

        wp_insert_post(
            array(
                'comment_status' => 'close',
                'ping_status' => 'close',
                'post_author' => 1,
                'post_title' => 'Empresa',
                'post_name' => 'nossa-empresa',
                'post_status' => 'publish',
                'post_content' => $html_modelo_quem_somos,
                'post_type' => 'page',
                'post_parent' => ''
            )
        );
    }

    if (!get_page_by_title('Contato')) {
        wp_insert_post(
            array(
                'comment_status' => 'close',
                'ping_status' => 'close',
                'post_author' => 1,
                'post_title' => 'Contato',
                'post_name' => 'contato',
                'post_status' => 'publish',
                'post_content' => '',
                'post_type' => 'page',
                'post_parent' => ''
            )
        );
    }

    if (!get_page_by_title('Blog')) {
        wp_insert_post(
            array(
                'comment_status' => 'close',
                'ping_status' => 'close',
                'post_author' => 1,
                'post_title' => 'Blog',
                'post_name' => 'blog',
                'post_status' => 'publish',
                'post_content' => '',
                'post_type' => 'page',
                'post_parent' => ''
            )
        );
    }

    if (!get_page_by_title('Ficha cadastral')) {
        wp_insert_post(
            array(
                'comment_status' => 'close',
                'ping_status' => 'close',
                'post_author' => 1,
                'post_title' => 'Ficha Cadastral',
                'post_name' => 'ficha-cadastral',
                'post_status' => 'publish',
                'post_content' => '',
                'post_type' => 'page',
                'post_parent' => ''
            )
        );
    }


    /**
     * Criar menus
     */
    if (!term_exists('principal', 'nav_menu')) {
        $menu = wp_insert_term('Principal', 'nav_menu', array('slug' => 'principal'));


        $locations = get_theme_mod('nav_menu_locations');
        $locations['primary'] = $menu['term_id'];
        $locations['my_main_menu']  = $menu['term_id'];
        set_theme_mod('nav_menu_locations', $locations);


    }


    /*
     * Criar itens do menu
     *
     */

    $menu_exists = wp_get_nav_menu_object('Principal');


    if ($menu_exists) {

        $arrItensMenu = getAllItensMenu($menu_exists->term_id);


        $menu_id = $menu_exists->term_id;


        $pageHome = get_page_by_title('Home');
        $pageEstoque = get_page_by_title('Estoque');
        $pageContato = get_page_by_title('Contato');
        $pageBlog = get_page_by_title('Blog');


        if ($pageHome) {
            $exist_page = in_array($pageHome->ID, $arrItensMenu);
            if (!$exist_page) {
                wp_update_nav_menu_item($menu_id, 0, array(
                        'menu-item-title' => __('Home'),
                        'menu-item-object-id' => $pageHome->ID,
                        'menu-item-object' => 'page',
                        'menu-item-status' => 'publish',
                        'menu-item-type' => 'post_type',
                    )
                );
            }

        }

        if ($pageEstoque) {
            $exist_page = in_array($pageEstoque->ID, $arrItensMenu);
            if (!$exist_page) {
                wp_update_nav_menu_item($menu_id, 0, array(
                        'menu-item-title' => 'Estoque',
                        'menu-item-object-id' => $pageEstoque->ID,
                        'menu-item-object' => 'page',
                        'menu-item-status' => 'publish',
                        'menu-item-type' => 'post_type',
                    )
                );
            }

        }

        if ($pageContato) {
            $exist_page = in_array($pageContato->ID, $arrItensMenu);
            if (!$exist_page) {
                wp_update_nav_menu_item($menu_id, 0, array(
                        'menu-item-title' => 'Contato',
                        'menu-item-object-id' => $pageContato->ID,
                        'menu-item-object' => 'page',
                        'menu-item-status' => 'publish',
                        'menu-item-type' => 'post_type',
                    )
                );
            }

        }

        if ($pageBlog) {
            $exist_page = in_array($pageBlog->ID, $arrItensMenu);
            if (!$exist_page) {
                wp_update_nav_menu_item($menu_id, 0, array(
                        'menu-item-title' => 'Blog',
                        'menu-item-object-id' => $pageBlog->ID,
                        'menu-item-object' => 'page',
                        'menu-item-status' => 'publish',
                        'menu-item-type' => 'post_type',
                    )
                );
            }

        }


    }


    /**
     * Definir paginas padrao
     */
    $home = get_page_by_title('Home');
    $blog = get_page_by_title('Blog');

    if ($home) {
        update_option('show_on_front ', 'page');
        update_option('page_on_front ', $home->ID);
    }
    if ($blog) {
        update_option('page_for_posts ', $blog->ID);
    }


    wp_redirect(admin_url('/admin.php?page=alt_group_setup'));
    exit;

}

function getAllItensMenu($id_menu)
{

    $arrReturn = [];
    $arrItensMenu = wp_get_nav_menu_items($id_menu);

    foreach ($arrItensMenu as $itens) {

        $arrReturn[] = $itens->object_id;
    };

    return $arrReturn;
}