<?php

define('WP_THEMES_URI', get_template_directory_uri());
define('WP_CSS_URI', get_stylesheet_uri());

//require_once dirname(__FILE__) . '/lib/Api.php';
require_once dirname(__FILE__) . '/lib/function/config.php';
require_once dirname(__FILE__) . '/lib/function/menu.php';
require_once dirname(__FILE__) . '/lib/posttype.php';
require_once dirname(__FILE__) . '/lib/customfield.php';

function webp_upload_mimes($existing_mimes)
{
    $existing_mimes['webp'] = 'image/webp';
    return $existing_mimes;
}

add_filter('mime_types', 'webp_upload_mimes');

show_admin_bar(false);

function wpdocs_theme_name_scripts()
{
    wp_enqueue_script('jquery-js', WP_THEMES_URI . '/assets/js/jquery-3.4.1.min.js', array(), '3.4.1', true);
    wp_enqueue_script('bootstrap', WP_THEMES_URI . '/assets/vendors/bootstrap/js/bootstrap.min.js', array(), '4.3.1', true);
    wp_enqueue_script('owl-carousel', WP_THEMES_URI . '/assets/vendors/owl-carousel/owl.carousel.min.js', array(), '2.3.4', true);
    wp_enqueue_script('bootstrap-datepicker-js', WP_THEMES_URI . '/assets/vendors/bootstrap-datepicker/js/bootstrap-datepicker.min.js', array(), '2.3.4', true);
    wp_enqueue_script('webfont', WP_THEMES_URI . '/assets/js/webfont.js', array(), '1.0.0', true);
    wp_enqueue_script('magnific-popup', WP_THEMES_URI . '/assets/vendors/magnific-popup/jquery.magnific-popup.min.js', array(), '1.0.0', true);
    wp_enqueue_script('sweet-alert', WP_THEMES_URI . '/assets/vendors/sweetalert/sweetalert2.all.min.js', array(), '1.0.0', true);
    wp_enqueue_script('app', WP_THEMES_URI . '/assets/js/app.js', array(), '1.0.0', true);
}

add_action('wp_enqueue_scripts', 'wpdocs_theme_name_scripts');

function prefix_add_footer_styles()
{
    wp_enqueue_style('bootstrap', WP_THEMES_URI . '/assets/vendors/bootstrap/css/bootstrap.min.css', [], '4.3.1');
    wp_enqueue_style('material-design-icons', WP_THEMES_URI . '/assets/vendors/material-design/css/materialdesignicons.min.css', [], '1.0.0');
    wp_enqueue_style('fontawesome', WP_THEMES_URI . '/assets/vendors/fontawesome/css/all.min.css', [], '5.10.1');
    wp_enqueue_style('owl-carousel-css', WP_THEMES_URI . '/assets/vendors/owl-carousel/assets/owl.carousel.min.css', [], '5.10.1');
    wp_enqueue_style('bootstrap-datepicker', WP_THEMES_URI . '/assets/vendors/bootstrap-datepicker/css/bootstrap-datepicker.min.css');
    wp_enqueue_style('magnific-popup-css', WP_THEMES_URI . '/assets/vendors/magnific-popup/magnific-popup.css');
    wp_enqueue_style('sizing-css', WP_THEMES_URI . '/assets/css/sizing.css');
    wp_enqueue_style('sweet-css', WP_THEMES_URI . '/assets/vendors/sweetalert/sweetalert2.min.css');
    wp_enqueue_style('main-style', WP_CSS_URI, '', time());
}

add_action('wp_enqueue_scripts', 'prefix_add_footer_styles');
//add_action('get_footer', 'prefix_add_footer_styles');

add_theme_support('title-tag');

function asset($name, $echo = true)
{
    $uri = sprintf('%s/assets/%s', WP_THEMES_URI, $name);
    if (!$echo) {
        return $uri;
    }

    echo $uri;
}

add_image_size('blog', 590, 370, true);
add_image_size('blog_sm', 250, 190, true);

add_theme_support('post-thumbnails');

function add_theme_menu_function()
{
    register_nav_menus(array(
        'primary' => 'Primary Navigation',
    ));
}

add_action('after_setup_theme', 'add_theme_menu_function');

function get_feature_image($id, $size = null, $default = null)
{
    $a = get_post_thumbnail_id($id);
    $img = wp_get_attachment_image_src($a, $size);
    if (isset($img[0])) {
        return $img[0];
    }

    if ($default) {
        return asset('images/590x370.png', false);
    }
}

function get_post_image($id)
{
    $a = get_post_thumbnail_id($id);
    $img = wp_get_attachment_image_src($a, null);
    if ($img) {
        $url = $img[0];

        $thumbnail_id = get_post_thumbnail_id($id);
        $alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true);
    }
    return [
        'url' => $url,
        'alt' => $alt,
    ];
}

function get_id_by_slug($page_slug)
{
    $page = get_page_by_path($page_slug);
    if ($page) {
        return $page->ID;
    } else {
        return null;
    }
}

function get_cat_id_by_slug($slug, $return = 'id')
{
    $term = get_category_by_slug($slug);
    if ($return != 'id') {
        return $term;
    }

    return $term->term_id;
}

function get_cat_by_post($id)
{
    $category = get_the_category($id);
    foreach ($category as $cd) {
        return $cd;
    }
}

function get_cats_link_by_post($id)
{
    $category = get_the_category($id);
    $items = [];
    foreach ($category as $cd) {
        $items[] = sprintf('<a href="%s">%s</a>', get_category_link($cd->term_id), $cd->name);
    }

    return implode(' ', $items);
}

function short_content($content, $length = 140)
{
    $content = html_entity_decode($content);
    $content = str_replace('&nbsp;', '', trim($content));
    $cleanString = filter_var($content, FILTER_SANITIZE_STRING);
    $msg = iconv_substr(strip_tags($cleanString), 0, $length, "UTF-8");
    if (strlen($msg) > $length) {
        $msg = rtrim($msg);
        $msg .= '...';
    }
    return $msg;
}

add_action('wp_enqueue_scripts', 'my_enqueue_function');

function my_enqueue_function()
{
    wp_enqueue_script('wp-util');
}

add_action('wp_ajax_nopriv_get_data', 'my_ajax_handler');
add_action('wp_ajax_get_data', 'my_ajax_handler');

function my_ajax_handler()
{
    global $wpdb;
    //echo json_encode($_POST);

    $validate = [
        'name', 'phone', 'email',
    ];
    foreach ($validate as $value) {
        if (empty($_POST[$value])) {
            return wp_send_json_success([
                'status' => 'error',
                'message' => 'กรุณากรอกข้อมูลให้ครบ',
            ]);
        }

    }

    $message = 'ชื่อ :  ' . $_POST['name'] . "\n";
    $message .= 'หมายเลขโทรศัพท์  : ' . $_POST['phone'] . "\n";
    $message .= 'อีเมล์  :' . $_POST['email'] . "\n";
    $message .= 'ท่านมีตำแหน่งที่ตั้งล็อกเกอร์พร้อมใช้หรือไม่  :' . ($_POST['locker'] == 1 ? 'มีแล้ว' : 'ยังไม่มี') . "\n";
    $message .= 'ที่ตั้งของล็อกเกอร์  :' . ($_POST['place'] == 1) . "\n";

    $token = config('setting.line_token', false);
    if ($message and $token) {

        $queryData = array('message' => $message);
        $queryData = http_build_query($queryData, '', '&');
        $headerOptions = array(
            'http' => array(
                'method' => 'POST',
                'header' => "Content-Type: application/x-www-form-urlencoded\r\n"
                . 'Authorization: Bearer ' . $token . "\r\n"
                . 'Content-Length: ' . strlen($queryData) . "\r\n",
                'content' => $queryData,
            ),
        );
        $context = stream_context_create($headerOptions);
        $result = file_get_contents('https://notify-api.line.me/api/notify', false, $context);

        return wp_send_json_success([
            'status' => 'success',
        ]);
    }

    return wp_send_json_success([
        'status' => 'error',
        'message' => 'ไม่สามารถส่งข้อมูลได้',
    ]);
}

/*
add_action('wpcf7_mail_sent', 'your_wpcf7_mail_sent_function');
function your_wpcf7_mail_sent_function($contact_form)
{
$title = $contact_form->title;
$submission = WPCF7_Submission::get_instance();
if ($submission) {
$posted_data = $submission->get_posted_data();
}
if ('Reagistation' == $title) {
$name = strtolower($posted_data['text-name']);
$name = strtolower(str_replace(' ', '_', $name));
$email = strtolower($posted_data['email']);
$phone = strtolower($posted_data['phone']);
$Areyouarealtor = $posted_data['Areyouarealtor'];
$ayor = strtolower($Areyouarealtor['0']);

}
}
 */

add_action('wpcf7_mail_sent', 'your_wpcf7_mail_sent_function');
function your_wpcf7_mail_sent_function($contact_form)
{
    $title = $contact_form->title;
    $submission = WPCF7_Submission::get_instance();
    if ($submission) {
        $posted_data = $submission->get_posted_data();

        $message = 'Email : ' . $posted_data['email'] . "\n";
        $message .= 'Name : ' . $posted_data['uname'] . "\n";
        $message .= 'Phone : ' . $posted_data['phone'] . "\n";
        //$message .= 'Subject : ' . $posted_data['subject'] . "\n";
        $message .= 'Message : ' . $posted_data['msg'];

        $token = config('setting.line_token', false);
        // $token = 'HTezgHZ4FhQ2Wy4uCom07OdYbK5B8PuMhv0EwtbudU8';
        // $token = 'qT8rLRmcV64TT1lu3g6z0FV9vKTPVIkiXLQusjFVfEeqT8rLRmcV64TT1lu3g6z0FV9vKTPVIkiXLQusjFVfEe';
        if ($token) {
            $queryData = array('message' => $message);
            $queryData = http_build_query($queryData, '', '&');
            $headerOptions = array(
                'http' => array(
                    'method' => 'POST',
                    'header' => "Content-Type: application/x-www-form-urlencoded\r\n"
                    . 'Authorization: Bearer ' . $token . "\r\n"
                    . 'Content-Length: ' . strlen($queryData) . "\r\n",
                    'content' => $queryData,
                ),
            );
            $context = stream_context_create($headerOptions);
            @file_get_contents('https://notify-api.line.me/api/notify', false, $context);
        }
        //@file_put_contents(ABSPATH . '/mail.json', $message);
    }
}
