<?php
/**
 * Created by PhpStorm.
 * User: Zain Ul Abidin
 * Date: 12/31/2020
 * Time: 3:37 PM
 */

$last_synced = get_option("sync_time");
$site_url = get_site_url();
if ($last_synced == "") {
    $html = "<div style='color: red;' '>WHMCS is not yet synced</div>";
    $html = $html . "<div><a href='$site_url/wp-admin/admin.php?page=whmp-sync'>Click here to Sync</a></div>";
    return $html;
}else{
    $atts=shortcode_atts([
        'html_template' => '',
        'table_id' => '',
        'html_id' => '',
        'html_class' => 'whmpress whmpress_price_matrix_domain',
        'hide_search' => whmpress_get_option('pmd_hide_search'),
        'currency' => '',
        'show_tlds' => '',
        'show_tlds_wildcard' => '',
        'decimals' => whmpress_get_option('pmd_decimals'),
        'show_renewel' => whmpress_get_option('pmd_show_renewel'),
        'show_transfer' => whmpress_get_option('pmd_show_transfer'),
        'titles' => '',
        'search_label' => whmpress_get_option('pmd_search_label'),
        'search_placeholder' => whmpress_get_option('pmd_search_placeholder'),
        "show_disabled" => whmpress_get_option('pmd_show_disabled'),
        'pricing_slab' => "0",
        'combine_extension' => '',                          # Price, PriceCC
        'data_table' => '0',
        'num_of_rows' => whmpress_get_option('pmd_num_of_rows'),
        'replace_empty' => '-',
        'show_type' => '0',
        'style' => '',
        'show_addons' => 'yes',
        'style1' => '',
        'show_restore' => 'no',
    ], $atts);

    if (!defined('WCAP_VERSION')) {
        if ($atts['data_table'] == "yes") {
            //echo '<link rel="stylesheet" href="//cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">' . PHP_EOL;
            wp_enqueue_script('whmp_dataTables', WHMP_PLUGIN_URL . '/includes/DataTables/datatables.min.js', ['jquery'], false, true);
            wp_enqueue_style('whmp_dataTables-style', WHMP_PLUGIN_URL . '/includes/DataTables/datatables.min.css');
        }
    }


    $currency = !empty($atts['currency'])? whmp_get_currency($atts["currency"]): whmp_get_current_currency_id_i();
    //$currency = whmp_get_currency($atts["currency"]);


    $combine_extension = strtolower(trim($atts["combine_extension"]));
    if ($atts["table_id"] == "") {
        $table_id = 'table' . rand(111, 999);
    }

    # Getting WordPress DB object
    global $wpdb;

    # Getting symbol type
    $symbol_type = strtolower(whmpress_get_option('default_currency_symbol'));

    # Getting data from database
    $c = "";

    if ($atts["num_of_rows"] == "Default" || $atts["num_of_rows"] == 10) {
        $num_of_rows = whmpress_get_option('pmd_num_of_rows');
    }

    $WHMPress = new WHMPress();
    $Q = "SELECT dpt.`id` id, ";
    if ($combine_extension == "price" || $combine_extension == "pricecc") {
        $Q .= "GROUP_CONCAT(`extension` SEPARATOR ', ') extension";
    } else {
        $Q .= "dpt.`extension`, dpt.`dnsmanagement`, dpt.`emailforwarding`, dpt.`idprotection`, dpt.`order`, dpt.`group`";
    }
    $Q .= ", `msetupfee`, `qsetupfee` FROM `" . whmp_get_pricing_table_name() . "` pt, `" . whmp_get_domain_pricing_table_name() . "` dpt WHERE dpt.id=`relid` AND
    `type`='[[[type]]]' AND `currency`=" . $currency;
    if (strtolower($atts["show_disabled"]) == "no" || $atts["show_disabled"] == "0" || $atts["show_disabled"] == false) {
        $Q .= " AND (`msetupfee`>0 OR `qsetupfee`>0)";
    }
    if (whmp_is_table_exists(whmp_get_clientgroups_table_name()) && !empty($pricing_slab)) {
        $Q .= " AND `tsetupfee` IN (SELECT `id` tsetupfee FROM `" . whmp_get_clientgroups_table_name() . "` WHERE id='$pricing_slab' OR `groupname`='$pricing_slab')";
    } else {
        $Q .= " AND `tsetupfee`='0'";
    }

    // Get Addon pricing if enabled.

    if (trim($atts["show_tlds"]) <> "") {
        $show_tlds = explode(",", $atts["show_tlds"]);
        $show_tlds = "'" . implode("','", $show_tlds) . "'";
        $Q .= " AND `extension` IN (" . $show_tlds . ")";
    } else if (trim($atts["show_tlds_wildcard"]) <> "") {
        $Q .= " AND `extension` LIKE '%" . $atts["show_tlds_wildcard"] . "%'";
    }

    if ($combine_extension == "pricecc") {
        $Q .= " AND `extension` IN (SELECT `extension` FROM `" . whmp_get_domain_pricing_table_name() . "` WHERE LENGTH(`extension`)-LENGTH(REPLACE(`extension`,'.',''))='2')";
    }

    if ($combine_extension == "price" || $combine_extension == "pricecc") {
        $Q .= " GROUP BY `msetupfee`, `qsetupfee`";
    }

    $Q .= " ORDER BY `order`";

    $type = "domainregister";
    $Q = str_replace("[[[type]]]", $type, $Q);


    $rows = $wpdb->get_results($Q, ARRAY_A);

    $type = "domainrenew";

    $rows2 = $wpdb->get_results(str_replace("[[[type]]]", $type, $Q), ARRAY_A);

    $type = "domaintransfer";

    $rows3 = $wpdb->get_results(str_replace("[[[type]]]", $type, $Q), ARRAY_A);

    $all_cats  = array();
    foreach ($rows as $k => $row) {
        $cats = $WHMPress->get_tld_categories($row['extension']);
        $rows[$k]['categories'] = implode(", ", $cats);
        array_push($all_cats,$cats);
    }

    $all_uniqu_cats = array_unique(call_user_func_array('array_merge',$all_cats));
    /*
     * Add Addons
     */
    $tlds_data = [];

    if ($atts["show_addons"] == 'yes') {
        $tmp = $WHMPress->get_domain_addon_price();

        foreach ($rows as &$row) {
            //Check if addon is enabled, if so set its value.
            if ($row['dnsmanagement'] == "1") {
                $row['dnsmanagement'] = $tmp['msetupfee'];
            } else {
                $row['dnsmanagement'] = "-1";
            }

            if ($row['emailforwarding'] == "1") {
                $row['emailforwarding'] = $tmp['qsetupfee'];
            } else {
                $row['emailforwarding'] = -1;
            }
            if ($row['idprotection'] == "1") {
                $row['idprotection'] = $tmp['ssetupfee'];
            } else {
                $row['idprotection'] = -1;
            }
        }
    }

    /*
     * Add Price Info
     */
    foreach ($rows as &$row) {
        $add_data = $WHMPress->get_domain_additional_data($row['id']);
        $row = array_merge($row, $add_data);

        $temp = $WHMPress->get_domain_price_bulk([
            "extension" => $row['extension'],
            "currency" => $currency,
            "pricing_slab" => $atts['pricing_slab'],
        ]);

        $row["registration-1"] = $temp["registration"]["1"];
        $row["registration-2"] = $temp["registration"]["2"];

        $row["registration-1"] = $temp["registration"]["1"];
        $row["registration-2"] = $temp["registration"]["2"];

        $row["renewal-1"] = $temp["renewal"]["1"];
        $row["renewal-2"] = $temp["renewal"]["2"];

        $row["transfer-1"] = $temp["transfer"]["1"];
        $row["transfer-2"] = $temp["transfer"]["2"];

        $row["registration"] = $temp["registration"];
        $row["renew"] = $temp["renewal"];
        $row["transfer"] = $temp["transfer"];

        unset ($row["msetupfee"]);
        unset ($row["qsetupfee"]);
        // select minimum years
        // check if minimum is years
        if (floatval($temp["registration"]["1"]) < 0 && floatval($temp["registration"]["2"]) > 0) {
            $field = "qsetupfee";
            $row["_registration"] = $temp["registration"]["2"];;
            $row["_transfer"] = $temp["transfer"]["2"];;
            $row["_renewal"] = $temp["renewal"]["2"];;
            $row["_years"] = 2;
            // check if minimum is one year
        } elseif (floatval($temp["registration"]["1"]) > 0) {
            $field = "msetupfee";
            $row["_registration"] = $temp["registration"]["1"];
            $row["_transfer"] = $temp["transfer"]["1"];
            $row["_renewal"] = $temp["renewal"]["1"];
            $row["_years"] = 1;
        } else {
            $field = $atts["replace_empty"];
            $row["_registration"] = $atts["replace_empty"];
            $row["_transfer"] = $atts["replace_empty"];
            $row["_renewal"] = $atts["replace_empty"];
            $row["_years"] = $atts["replace_empty"];
        }
        $tlds_data[] = $row;
    }

    # Generating output string
    $str = $table_header = '';

    if ($atts["data_table"] == '1' || strtolower($atts["data_table"]) == 'yes') {
        $str .= "\n<script>
        jQuery(function(){
            jQuery('table#{$table_id}').DataTable({
                \"iDisplayLength\": $num_of_rows
            });
        });
        </script>\n";
    }

    /*if (strtolower($atts["hide_search"]) == "yes") {
        $str .= "<script>
            jQuery(function(){
                jQuery('input#search_{$table_id}').quicksearch('table#{$table_id} tbody tr');
            });
            </script>";
    }*/

    $table = $top = $head = $trow = $total_rows = $tail = '';

    // TODO: Rename hide_search to hide_category_panel
    if (strtolower($atts["hide_search"]) == "yes") {
        $table_header = '<div class="whmpress_price_matrix_header"></div>';

        // TLD Types Toggle container
        $tld_type_toggles = "";
        $tld_types = $all_uniqu_cats;
        $tld_type_toggles = '<div class="whmp_domain_type_toggle_container">';
        $tld_type_toggles .= '<label>'. __("Type", "whmpress") . '</label>';
        $tld_type_toggles .= '<span class="whmp_domain_type_toggle" data-tld-type="all">' .  __("All", "whmpress") . '</span>';
        foreach ($tld_types as $tld_type) {
            $tld_type_toggles .= '<span class="whmp_domain_type_toggle" data-tld-type="' . $tld_type . '">' . $tld_type . '</span>';
        }
        $tld_type_toggles .= '</div>';

        $table_header = '<div class="whmpress_price_matrix_header">';
        $table_header .=  $tld_type_toggles;
        $table_header .= '<div style="clear: both"></div>';
        $table_header .= '</div>';
    }

    $head = '<div class="whmpress whmpress_price_matrix_domain style_1 multi_durations">';
    $head .= $table_header;
    $head .= '<input type="hidden" name="duration" class="duration" value="1">';
    $head .= '<table id="' . $table_id . '">';
    $head .= '<thead>';
    $head .= '<tr>';
    $head .= '<th>' . __('Domain', 'whmpress') . '</th>';
    $head .= '<th>' . __('Register', 'whmpress') . '</th>';
    $head .= '<th>' . __('Transfer', 'whmpress') . '</th>';
    $head .= '<th>' . __('Renew', 'whmpress') . '</th>';
    $head .= '</tr>';
    $head .= '</thead>';

    foreach ($tlds_data as $row) {
        $group_class = $group_span = '';

        $data_price_register = '';
        $data_price_renew = '';
        $data_price_transfer = '';

        //build data array
        // data content for registration
        foreach ($row['registration'] as $key => $price) {
            $tmp = whmp_apply_symbol(format_price($price, false, $atts["decimals"]), $currency,$symbol_type );
            $data_price_register .= 'data-price' . $key . ' = "' . $tmp . '" ';
        }

        // data content for renewal
        foreach ($row['renew'] as $key => $price) {
            $tmp = whmp_apply_symbol(format_price($price, false, $atts["decimals"]), $currency,$symbol_type);
            $data_price_renew .= 'data-price' . $key . ' = "' . $tmp . '" ';
        }

        // data content for transfer
        foreach ($row['transfer'] as $key => $price) {
            $tmp = whmp_apply_symbol(format_price($price, false, $atts["decimals"]), $currency,$symbol_type);
            $data_price_transfer .= 'data-price' . $key . ' = "' . $tmp . '" ';
        }

        $addon_domains_html = "";
        if ($atts["show_addons"] == 'yes') {

            $addon_domains = [
                'Domain Forwarding' => [
                    'icon' => '<i class="fa fa-share"></i> ',
                    'price' => $row['dnsmanagement']
                ],
                'Email Forwarding' => [
                    'icon' => '<i class="fa fa-check"></i> ',
                    'price' => $row['emailforwarding']
                ],
                'Privacy Protection' => [
                    'icon' => '<i class="fa fa-user-secret"></i> ',
                    'price' => $row['idprotection']
                ]
            ];

            //unset elements that are -1
            foreach ($addon_domains as $addon_key => $addon_domain) {
                if ($addon_domain['price'] == -1) {
                    //echo "unsetting";
                    unset($addon_domains[$addon_key]);
                }
            }

            // do not output html if there is no addon to show.

            if ($row['dnsmanagement'] >= 0 || $row['emailforwarding'] >= 0 || $row['idprotection'] >= 0) {

                $addon_domains_html .= '<div class="whmp_dropdown_outer">';
                $addon_domains_html .= '<span class="whmp_dropdown_toggle">Add Ons</span>';
                $addon_domains_html .= '<ul class="whmp_dropdown_inner whmp_domain_addons">';
                foreach ($addon_domains as $addon_key => $addon_domain) {
                    $addon_domains_html .= '<li>';
                    $addon_domains_html .= $addon_domain['icon'];
                    $addon_domains_html .= '<span class="whmp_addon_label">' . $addon_key . '</span> ';
                    $addon_domains_html .= '<span class="whmp_addon_price">' . $addon_domain['price'] . '</span> ';
                    $addon_domains_html .= '</li>';
                }
                $addon_domains_html .= '</ul></div>';
            } // end if there is no addon set for todain
        }//if addon set to yes

        $type_filter = ' data-tld-types="' . $row['categories'] . '"';

        $trow = '<tr class="whmp_domain_matrix_row ' . $group_class . '"' . $type_filter . '>';
        $trow .= '<td data-content="domain" class="whmp_domain">' . $row['extension'] . $addon_domains_html . '</td>';

        $tmp = whmp_apply_symbol(format_price($row['_registration'], false, $atts["decimals"]), $currency,$symbol_type);
        $trow .= '<td data-content="Register" class="whmp_price whmp_register_price" ' . $data_price_register . '><span class="whmp_show_price">' . $row['promo_register_off'] . '</span><span class="whmp_actual_price">' . $tmp . '</span></td>';

        $tmp = whmp_apply_symbol(format_price($row['_transfer'], false, $atts["decimals"]), $currency,$symbol_type);
        $trow .= '<td data-content="Transfer" class="whmp_price whmp_transfer_price" ' . $data_price_transfer . '><span class="whmp_show_price">' . $row['promo_transfer_off'] . '</span><span class="whmp_actual_price">' . $tmp . '</span></td>';

        $tmp = whmp_apply_symbol(format_price($row['_renewal'], false, $atts["decimals"]), $currency,$symbol_type);
        $trow .= '<td data-content="Renew" class="whmp_price whmp_renew_price" ' . $data_price_renew . '><span class="whmp_show_price">' . $row['promo_renew_off'] . '</span><span class="whmp_actual_price">' . $tmp . '</span></td>';

        $trow .= '</tr>';
        $total_rows .= $trow;
    }

    $tail .= '</tbody></table></div>';
    $table = $head . $total_rows . $tail;

    $html_message  = '<div class="whmpress_html_content whcom_row" style="margin-right: 10px; margin-left: 10px">';
    $html_message .=  whmpress_get_option('first_html_message');
    $html_message .= '</div>';

    return $table.$html_message;

}
