<?php
    function dc_services_page_handler()
    {
        $table = new ServiceTable();
        $table->prepare_items();
        
        $message = '';
        if ('delete' === $table->current_action() && is_array($_REQUEST['id'])) {
            $message = '<div class="updated below-h2" id="message"><p>' . sprintf(__('Items deleted: %d', 'dc'),
                    count($_REQUEST['id'])) . '</p></div>';
        }
        ?>
		<div class="wrap">
			<div class="icon32 icon32-posts-post" id="icon-edit"><br/></div>
			<h2><?php _e('Services', 'dc') ?> <a class="add-new-h2"
			                                     href="<?php echo get_admin_url(get_current_blog_id(),
                                                     'admin.php?page=services_form'); ?>"><?php _e('Add new',
                        'dc') ?></a>
			</h2><?php echo $message; ?>
			<form id="services-table" method="POST">
				<input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>"/>
                <?php $table->display() ?>
			</form>
		</div>
        <?php
    }
    
    function dc_services_form_page_handler()
    {
        global $wpdb;
        $table_name    = DC_SERVICES;
        $regions_table = DC_REGIONS;
        $message       = '';
        $notice        = '';
        
        $default = array(
            'id'              => 0,
            'service_name'    => '',
            'plural'          => '',
            'syn_1'           => '',
            'syn_2'           => '',
            'syn_3'           => '',
            'alias'           => '',
            'description'     => '',
            'title'           => null,
            'seo_h1'          => '',
            'seo_description' => '',
            'content'         => '',
            'seo_excerpt'     => '',
            'template_id'     => '1',
            'regions'         => null
        );
        
        if (isset($_REQUEST['nonce']) && wp_verify_nonce($_REQUEST['nonce'], basename(__FILE__))) {
            $item       = shortcode_atts($default, $_REQUEST);
            $item_valid = dc_service_validate_service($item);
            if ($item_valid === true) {
                if ($item['id'] == 0) { // new service
                    if (empty($item['alias'])) {
                        $item['alias'] = sanitize_title($item['service_name']);
                    }
                    $item['content']     = wp_kses_post(stripslashes($item['content']));
                    $item['seo_excerpt'] = wp_kses_post(stripslashes($item['seo_excerpt']));
                    $result              = $wpdb->insert($table_name, $item);
                    $item['id']          = $wpdb->insert_id;
                    if ($result) {
                        $message = __('Service was successfully saved', 'dc');
                    } else {
                        $notice = __('There was an error while saving Service', 'dc');
                    }
                } else {
                    
                    if (empty($item['alias'])) {
                        $item['alias'] = sanitize_title($item['service_name']);
                    }
                    $item['content']     = wp_kses_post(stripslashes($item['content']));
                    $item['seo_excerpt'] = wp_kses_post(stripslashes($item['seo_excerpt']));
                    
                    
                    $regions = isset($_REQUEST['region']) ? $_REQUEST['region'] : array();
                    if (is_array($regions)) {
                        $regions = implode(',', $regions);
                    }
                    
                    if ( ! empty($regions)) {
                        $service_id = $item['id'];
                        $wpdb->query("UPDATE $regions_table SET services=0"); // TODO: сделать нормальный процессинг снятых чекбоксов
                        $wpdb->query("UPDATE $regions_table SET services=$service_id WHERE id IN ($regions)");
                    }
                    unset ($item['regions']);
                    $result = $wpdb->update($table_name, $item, array('id' => $item['id']));
                    if ($result) {
                        $message = __('Item was successfully updated', 'dc');
                    } else {
                        $notice = __('There was an error while updating item', 'dc');
                    }
                }
            } else {
                $notice = $item_valid;
            }
        } else {
            
            $item = $default;
            if (isset($_REQUEST['id'])) {
                $item = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $_REQUEST['id']),
                    ARRAY_A);
                if ( ! $item) {
                    $item   = $default;
                    $notice = __('Item not found', 'dc');
                }
            }
        }
        
        add_meta_box('dc_services_form_meta_box', __('Services data', 'dc'), 'dc_services_form_meta_box_handler',
            'service', 'normal', 'default');
        
        ?>
		<div class="wrap">
			<div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
			<h2><?php _e('Service', 'dc') ?> <a class="add-new-h2" href="<?php echo get_admin_url(get_current_blog_id(),
                    'admin.php?page=dc-catalog-services'); ?>"><?php _e('back to services list', 'dc') ?></a>
			</h2><?php if ( ! empty($notice)): ?>
				<div id="notice" class="error"><p><?php echo $notice ?></p></div><?php endif;
                if ( ! empty($message)): ?>
					<div id="message" class="updated"><p><?php echo $message ?></p></div><?php endif; ?>

			<form id="form" method="POST">
				<input type="hidden" name="nonce" value="<?php echo wp_create_nonce(basename(__FILE__)) ?>"/>
				<input type="hidden" name="id" value="<?php echo $item['id'] ?>"/>
				<div class="metabox-holder" id="poststuff">
					<div id="post-body">
						<div id="post-body-content"><?php do_meta_boxes('service', 'normal', $item); ?>
							<input type="submit" value="<?php _e('Save', 'dc') ?>" id="submit" class="button-primary"
							       name="submit">
						</div>
					</div>
				</div>
			</form>
		</div>
        <?php
    }
    
    function dc_services_form_meta_box_handler($item)
    {
        $templates = get_templates();
        $regions   = get_regions();
        
        ?>
		<tbody>
		<div class="formdatabc">
			<form>
				<div class="form3bc">
					<p>
						<label for="service_name"><?php _e('Service', 'dc') ?>*</label>
						<br>
						<input id="service_name" name="service_name" type="text"
						       value="<?php echo esc_attr($item['service_name']) ?>" required>
					</p>
					<p>
						<label for="plural"><?php _e('Plural', 'dc') ?></label>
						<br>
						<input id="plural" name="plural" type="text" value="<?php echo esc_attr($item['plural']) ?>">
					</p>
					<p>
						<label for="alias"><?php _e('Alias', 'dc') ?></label>
						<br>
						<input id="alias" name="alias" type="text" value="<?php echo esc_attr($item['alias']) ?>">
					</p>
				</div>
				<div class="form3bc">
					<p>
						<label for="syn_1"><?php _e('Synonym 1', 'dc') ?></label>
						<br>
						<input id="syn_1" name="syn_1" type="text" value="<?php echo esc_attr($item['syn_1']) ?>">
					</p>
					<p>
						<label for="syn_2"><?php _e('Synonym 2', 'dc') ?></label>
						<br>
						<input id="syn_2" name="syn_2" type="text" value="<?php echo esc_attr($item['syn_2']) ?>">
					</p>
					<p>
						<label for="syn_3"><?php _e('Synonym 3', 'dc') ?></label>
						<br>
						<input id="syn_3" name="syn_3" type="text" value="<?php echo esc_attr($item['syn_3']) ?>">
					</p>

				</div>
				<div class="form2bc">
					<p>
						<label for="description"><?php _e('Description', 'dc') ?></label>
						<br>
						<input id="description" name="description" type="text"
						       value="<?php echo esc_attr($item['description']) ?>">
					</p>
					<p>
						<label for="title"><?php _e('Title', 'dc') ?></label>
						<br>
						<input id="title" name="title" type="text" value="<?php echo esc_attr($item['title']) ?>">
					</p>
				</div>
				<div class="form2bc">
					<p>
						<label for="seo_h1"><?php _e('H1', 'dc') ?></label>
						<br>
						<input id="seo_h1" name="seo_h1" type="text" value="<?php echo esc_attr($item['seo_h1']) ?>">
					</p>
					<p>
						<label for="seo_description"><?php _e('SEO Description', 'dc') ?></label>
						<br>
						<input id="seo_description" name="seo_description" type="text"
						       value="<?php echo esc_attr($item['seo_description']) ?>">
					</p>
				</div>
				<div class="form2bc">
					<p>
						<label for="template_id"><?php _e('Template', 'dc') ?></label>
						<br>
						<select id="template_id" name="template_id"><?php
                                foreach ($templates as $template) {
                                    ($template->id == $item['template_id']) ? $selected = ' selected' : $selected = '';
                                    ?>
									<option value="<?php echo esc_attr($template->id); ?>"<?php echo $selected; ?>><?php echo esc_attr($template->template_name); ?></option>
                                    <?php
                                }
                            ?>
						</select>
					</p>
				</div>
				<div class="form1bc">
					<p>
					<h3>Regions allowed:</h3>
					<ul class="regions_list"><?php
                            /*echo '<pre>';
                            print_r($regions);
                            echo '</pre>';*/
                            foreach ($regions as $region) {
                                $checked = ($region->services == $item['id']) ? ' checked ' : '';
                                ?>
								<li>
									<label>
										<input type="checkbox" name="region[]"
										       value="<?php echo $region->id; ?>" <?php echo $checked; ?>><?php echo $region->region_name; ?>
									</label>
								</li>
                                <?php
                            }
                        ?></ul>
					</p>
				</div>
				<div class="form1bc">
					<p>
					<hr/>
					<label for="seo_excerpt"><?php _e('Excerpt:', 'dc') ?></label>
					<br><?php
                        $exc_id  = "seo_excerpt";
                        $excerpt = stripslashes($item['seo_excerpt']);
                        wp_editor($excerpt, strtolower($exc_id));
                    ?>
					</p>
					<p>
					<hr/>
					<label for="content"><?php _e('Content:', 'dc') ?></label>
					<br><?php
                        $id      = "content";
                        $content = stripslashes($item['content']);
                        wp_editor($content, strtolower($id));
                    ?>
					</p>
				</div>
			</form>
		</div>
		</tbody>
        <?php
    }
    
    function dc_service_validate_service($item)
    {
        $messages = array();
        
        if (empty($item['service_name'])) {
            $messages[] = __('Service Name is required', 'dc');
        }/*
            if (empty($item['content'])) $messages[] = __('Last Name is required', 'wpbc');
            if (!empty($item['email']) && !is_email($item['email'])) $messages[] = __('E-Mail is in wrong format', 'wpbc');
            if(!empty($item['phone']) && !absint(intval($item['phone'])))  $messages[] = __('Phone can not be less than zero');
            if(!empty($item['phone']) && !preg_match('/[0-9]+/', $item['phone'])) $messages[] = __('Phone must be number');*/
        
        if (empty($messages)) {
            return true;
        }
        
        return implode('<br />', $messages);
    }