<?php
/**
 * Created by PhpStorm.
 * User: Hani
 * Date: 8/11/2018
 * Time: 6:54 PM
 */

//discount_amount - role - min_basket - max_basket - type -  categories - products
$current_url = admin_url().'admin.php?page=woo2app/discount/index.php&tab=discount';

$discount_amount = "";
$role = "";
$min_basket = "";
$max_basket = "";
$type = "";
$categories = array();
$products = array();

if(isset($_POST['create'])) {
	global $wpdb;
	$results = $wpdb->get_results( "select post_id, meta_key from $wpdb->postmeta where meta_value like '". $_POST['role'] ."'", ARRAY_A );
	if(!$results) {
		$array = array(
			'post_title' => 'discount - app - draft',
			'post_content' => '',
			'post_type' => 'woo2app_discount',
			'post_status' => 'draft',
		);
		if ($post = wp_insert_post($array)) {
			add_post_meta($post, 'role', $_POST['role']);
			add_post_meta($post, 'discount_amount', $_POST['discount_amount']);
			add_post_meta($post, 'min_basket', $_POST['min_basket']);
			add_post_meta($post, 'max_basket', $_POST['max_basket']);
			add_post_meta($post, 'type', $_POST['type']);
			add_post_meta($post, 'categories', (isset($_POST['categories'])) ? $_POST['categories'] : array());
			add_post_meta($post, 'products', (isset($_POST['products'])) ? $_POST['products'] : array());
		}
	}
	else{
		?>
        <div class="notice notice-danger is-dismissible">
            <p> <?php _e('The role is duplicate, Choose another role. ', 'woo2app'); ?></p>
        </div>
		<?php
	}

}
elseif(isset($_REQUEST['submit_edit'])){
	$post_id = $_POST['delete_id'];

	update_post_meta($post_id, 'role', $_POST['role']);
	update_post_meta($post_id, 'discount_amount', $_POST['discount_amount']);
	update_post_meta($post_id, 'min_basket', $_POST['min_basket']);
	update_post_meta($post_id, 'max_basket', $_POST['max_basket']);
	update_post_meta($post_id, 'type', $_POST['type']);
	update_post_meta($post_id, 'categories', (isset($_POST['categories'])) ? $_POST['categories'] : array());
	update_post_meta($post_id, 'products', (isset($_POST['products'])) ? $_POST['products'] : array());
	//exit();
}

if(isset($_GET['action']) && isset($_GET['field'])) {
	if ($_GET['action'] == 'delete' && $_GET['field'] != '') {
		$post_id = $_GET['field'];
		if (wp_delete_post($post_id)) {
			?>
            <div class="notice notice-success is-dismissible">
                <p> <?php _e('The case was deleted correctly. ', 'woo2app'); ?></p>
            </div>
			<?php
		} else {
			?>
            <div class="notice notice-danger is-dismissible">
                <p>  <?php _e('Sorry, we encountered a problem. Please try again.', 'woo2app'); ?></p>
            </div>
			<?php
		}
	}
}

$args      = array(
	'post_type'   => 'woo2app_discount',
	'post_status' => 'draft',
	'posts_per_page' => -1,
);
$register_role = array();
$the_query = get_posts( $args );
foreach ( $the_query as $f ) {
	$register_role[] = get_post_meta($f->ID , 'role' , true);
}

$editable = 0;
$edit_role = "";
if(isset($_GET['action']) && isset($_GET['field'])){
	if($_GET['action'] == 'edit' && $_GET['field'] != ''){
		$editable = 1;
		$post_id = $_GET['field'];
		$discount_amount = get_post_meta($post_id , 'discount_amount' , true);
		$edit_role = get_post_meta($post_id , 'role' , true);
		$min_basket = get_post_meta($post_id , 'min_basket' , true);
		$max_basket = get_post_meta($post_id , 'max_basket' , true);
		$type = get_post_meta($post_id , 'type' , true);
		$categories = get_post_meta($post_id , 'categories' , true) ?: array();
		$products = get_post_meta($post_id , 'products' , true) ?: array();
	}
}
wp_register_style('select2.min.css', WOO2APP_CSS_URL . 'select2.min.css');
wp_enqueue_style('select2.min.css'.WOO2APP_FILES_VER);
wp_enqueue_script('select2.min.js'.WOO2APP_FILES_VER, WOO2APP_JS_URL . 'select2.min.js');
?>
    <h2> <?php _e('New Discount', 'woo2app'); ?> </h2>
    <form action="" method="post">
        <table class="form-table ">
            <tbody>
            <tr valign="top" class="">
                <th scope="row" class="titledesc">
                    <label>  <?php _e('Role', 'woo2app'); ?> </label>
                </th>
                <td class="forminp forminp-text">
                    <select  class="regular-text" name="role" required="required">
						<?php
						$roles = wp_roles();
						foreach ($roles->roles as $r => $rr){
							$i = 0;
							foreach ($rr['capabilities'] as $cap => $val){
								if($cap == 'mr2app_discount'){
									$i ++;
									?>
                                    <option <?= selected($edit_role, $r)?> value="<?= $r; ?>"> <?= $rr['name'];?></option>
									<?php
								}
							}
							?>

							<?php
						}
						?>
                    </select>
                </td>
            </tr>

            <tr valign="top" class="">
                <th scope="row" class="titledesc">
                    <label>   <?php _e('Minimum Cart', 'woo2app'); ?> </label>
                </th>
                <td class="forminp">
                    <input type="text" class="regular-text" value="<?= $min_basket; ?>" name="min_basket" id="min_basket">
                </td>
            </tr>

            <tr valign="top" class="">
                <th scope="row" class="titledesc">
                    <label>   <?php _e('Maximum Order ', 'woo2app'); ?> </label>
                </th>
                <td class="forminp">
                    <input type="text" class="regular-text" value="<?= $max_basket; ?>" name="max_basket" id="max_basket">
                </td>
            </tr>

            <tr valign="top" class="">
                <th scope="row" class="titledesc">
                    <label>   <?php _e('Type', 'woo2app'); ?> </label>
                </th>
                <td class="forminp">
                    <strong>  <?php _e('Percent', 'woo2app'); ?> </strong> <input
                            type="radio" <?= ($type == 'percent') ? 'checked' : '' ?> name="type" checked
                            value="percent">
                    <strong>  <?php _e('Fixed', 'woo2app'); ?> </strong> <input
                            type="radio" <?= ($type == 'constant') ? 'checked' : '' ?> name="type"
                            value="constant">
                </td>
            </tr>

            <tr valign="top" class="">
                <th scope="row" class="titledesc">
                    <label>   <?php _e('Amount', 'woo2app'); ?> </label>
                </th>
                <td class="forminp">
                    <input type="text" class="regular-text" required value="<?= $discount_amount; ?>" name="discount_amount"  id="discount_amount">
                </td>
            </tr>

            <tr valign="top" class="">
                <th scope="row" class="titledesc">
                    <label> <?php _e('Allowed Categories', 'woo2app'); ?> </label>
                </th>
                <td class="forminp">
                    <select name="categories[]"  multiple
                            class="js-example-basic-single regular-text"
                            title=" <?php _e('Select ... ', 'woo2app'); ?>">
                        <option value="0"
                                style="text-align:right;"> <?php _e('Please Select ...', 'woo2app'); ?></option>
						<?php
						$i=0;
						$cats = get_terms(array('product_cat'));
						foreach ($cats as $cat) {
							$i++;
							?>
                            <option <?= (in_array($cat->term_id,$categories)) ? 'selected' :''?> style="text-align:right;"  value="<?= $cat->term_id; ?>"><?= $cat->name; ?></option>
							<?php
						}
						?>
                    </select>
                </td>
            </tr>

            <tr valign="top" class="">
                <th scope="row" class="titledesc">
                    <label>   <?php _e('Allowed Products', 'woo2app'); ?> </label>
                </th>
                <td class="forminp">
                    <select name="products[]" data-id="product"  multiple  class="js-data-example-ajax regular-text">
						<?php
						$_pf = new WC_Product_Factory();
						foreach ($products as $p){
							$_product = $_pf->get_product($p);
							if($_product){
								?>
                                <option selected value="<?= $_product->get_id()?>"><?= $_product->get_title()?></option>
								<?php
							}
						}
						?>
                    </select>
                </td>
            </tr>


            <tr >
                <th scope="row" class="titledesc">

                </th>
                <td class="forminp">
					<?php
					if($editable == 1){
						?>
                        <input type="submit" class="button button-primary" value=" <?php _e('Edit', 'woo2app'); ?>"
                               name="submit_edit"/>
                        <input type="hidden" name="delete_id" value="<?= $post_id?>" />
                        <a href="<?= $current_url; ?>" class="button">   <?php _e('New', 'woo2app'); ?> </a>
						<?php
					}
					else{
						?>
                        <input type="submit" class="button" value=" <?php _e('Save', 'woo2app'); ?>" name="create"/>
						<?php
					}
					?>
                </td>
            </tbody>
        </table>
    </form>


    <hr>

    <table class="wp-list-table widefat striped">
        <tbody>
        <tr valign="top" class="">
            <th scope="row" class="">
                <label > #  </label>
            </th>
            <th scope="row" class="">
                <label>   <?php _e('Role', 'woo2app'); ?>  </label>
            </th>
            <th scope="row" class="">
                <label>  <?php _e('Minimum order', 'woo2app'); ?>  </label>
            </th>
            <th scope="row" class="">
                <label>  <?php _e('Maximum order', 'woo2app'); ?>  </label>
            </th>
            <th scope="row" class="">
                <label>  <?php _e('Type', 'woo2app'); ?>  </label>
            </th>
            <th scope="row" class="">
                <label>  <?php _e('Amount of discount ', 'woo2app'); ?>  </label>
            </th>
            <th scope="row" class="">
                <label>  <?php _e('Edit / Delete', 'woo2app'); ?>  </label>
            </th>
        </tr>
		<?php
		$args   = array(
			'post_type'   => 'woo2app_discount',
			'post_status' => 'draft',
			'posts_per_page' => -1,
		);
		$the_query = get_posts( $args );
		$i = 0;
		foreach ($the_query as $f){
			$i++;
			?>
            <tr valign="top" class="">
                <th scope="row" class="">
                    <label > <?= $i; ?>  </label>
                </th>
                <th scope="row" class="">
                    <label > <?= get_post_meta($f->ID,'role' , true);?>  </label>
                </th>
                <th scope="row" class="">
                    <label > <?= get_post_meta($f->ID,'min_basket' , true);?>  </label>
                </th>
                <th scope="row" class="">
                    <label > <?= get_post_meta($f->ID,'max_basket' , true);?>  </label>
                </th>
                <th scope="row" class="">
                    <label > <?= get_post_meta($f->ID,'type' , true);?>  </label>
                </th>
                <th scope="row" class="">
                    <label > <?= get_post_meta($f->ID,'discount_amount' , true);?>  </label>
                </th>
                <th scope="row" class="">
                    <form action="" onsubmit="return confirm('Do you really want to submit the form?');" method="post" id="form_<?= $f->ID ?>">
                        <input type="hidden" name="delete_id" value="<?= $f->ID; ?>" />
                        <a class="button button-primary"
                           href="<?= $current_url . '&action=edit&field=' . $f->ID; ?>">  <?php _e('Edit', 'woo2app'); ?> </a>
                        <a class="button "
                           href="<?= $current_url . '&action=delete&field=' . $f->ID; ?>">  <?php _e('Delete', 'woo2app'); ?></a>
                        <!--<input type="submit" name="submit_delete" class="button button-danger" value="delete" />-->
                    </form>
                </th>
            </tr>
			<?php
		}
		?>
        </tbody>
    </table>

<?php
wp_enqueue_script( 'loadajax.js'.WOO2APP_FILES_VER , WOO2APP_JS_URL.'loadAjaxPosts.js', array('jquery'));
?>