<?php
/*
 * Plugin Name: Qcart
 * Version: 22.10.021742
 * Author: ComoQuiero
 * Author URI: https://qcart.app
 * Plugin URI: https://qcart.app
 * Description: Your plugin to automatically allow your users to add a shopping list cart for your recipes, display nutrition, and more!
 * Text Domain: comoquiero
 */

// stackoverflow.com/questions/6127559/wordpress-plugin-call-to-undefined-function-wp-get-current-user
add_action('init', function () {
    add_action('admin_post_nopriv_post_sync', "postSync");
    add_action('admin_post_nopriv_postsync', "postSync");

    // fetch("/wp-admin/admin-ajax.php?action=postsync", { method: "POST", body: JSON.stringify({ action: "postsync" }) });

    if (is_admin()) {
        include_once 'qcart-settings.php';
    } else {
        add_action('wp_enqueue_scripts', "QCART_scripts");
    }
});

function postSync()
{
    // $request = file_get_contents('php://input');
    // $data = json_decode($request, true);

    $id = $_POST['id'];
    $title = wp_strip_all_tags($_POST['title']);

    if (empty($id)) {
        http_response_code(400);
        die("missing id");
    }

    if (!is_numeric($id)) {
        http_response_code(400);
        die("not numberic id");
    }

    if (get_post_status($id)) {
        http_response_code(400);
        die("post $id already exists");
    }

    if (empty($title)) {
        http_response_code(400);
        die("missing title");
    }

    $postId = wp_insert_post(array(
        'ID' => $id,
        'post_title' => $title,
        'post_content' => $_POST['content'],
        'post_status' => 'publish',
        'post_date' => $date,
        'post_date_gmt' => $date,
        'post_modified' => $date,
        'post_modified_gmt' => $date,
    ));

    die("Inserted post $postId");
};

function QCART_scripts()
{
// HANDLE SHORTCODE [qcart]
    add_shortcode('qcart', function ($atts) {
        $q = $atts["q"] ? "qcart-" . $atts["q"] : "cq-parent";
        return "<div class='$q'></div>";
    });

// // DEPRECATED SHORTCODE [comoquiero]:
    // add_shortcode('comoquiero', function ($atts) {
    //     $q = $atts["q"] ? "qcart-" . $atts["q"] : "cq-parent";
    //     return "<div class='$q'></div>";
    // });

// LOCATION.SEARCH
    $q = "";

    $key = get_option('qcart_key');
    if (!empty($key)) {

        $supermarket = get_option('qcart_supermarket');
        $brands = get_option('qcart_brands');

        // KEY
        $q .= "?key=$key";

        // SUPERMARKET
        if (!empty($supermarket)) {
            $q .= "&smkt=$supermarket";
        }

        // BRANDS
        if (!empty($brands)) {
            $q .= "&brands=$brands";
        }
    }

// INJECT SCRIPT
    if (isset($_GET['test'])) {
        wp_enqueue_script('QCART_qrecipes', "https://s.comoquiero.abc/btn-test.js$q", array(), '', true);
    } else {
        wp_enqueue_script('QCART_qrecipes', "https://s.comoquiero.net/btn.js$q", array(), '', true);
    }
}
