<?php

function create_hosting_reviews()
{

    register_post_type('hosting_reviews',
        array(
            'labels' => array(
                'name' => __('Hosting Reviews'),
                'singular_name' => __('Hosting Review')
            ),
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'hosting_reviews'),
            'supports' => array( 'title', 'editor', 'thumbnail')
        )
    );
}


function vq_save_hosting_review($post_id)
{
    if (isset($_POST['vq_review_hosting_company'])) {
	    $new_value = $_POST['vq_review_hosting_company'];
        update_post_meta( $post_id, 'vq_review_hosting_company', $new_value );
    }
}


function vq_hosting_company_metabox($post, $metabox)
{
	$selected = get_post_meta( get_the_ID(), 'vq_review_hosting_company', true );
	$hosting_companies = json_decode(get_option('vq_hosting_companies_details'));
	if (!isset($hosting_companies)) {
		$hosting_companies = [];
    }
	?>

    <style>
        .hosting-company-meta {
            display: flex;
            align-items: center;
        }

        .hosting-company-meta label {
            width: 200px;
            text-align: center;
            font-weight: 500;
        }

        .hosting-company-meta select {
            width: 200px;
            height: 30px;
        }
    </style>

    <div class="hosting-company-meta">
        <label>Hosting Company: </label>
        <select name="vq_review_hosting_company" id="voodoo_dropdown">
		    <?php foreach ($hosting_companies as $company):  ?>
                <option value="<?php echo $company->slug;?>" <?php echo $selected === $company->slug ?  'selected' : '' ?> ><?php echo $company->name; ?></option>
		    <?php endforeach; ?>
        </select>
    </div>


	<?php
}

function vq_add_hosting_metaboxes()
{
	add_meta_box( 'vq-hosting-company-metabox', __( 'Hosting Company'), 'vq_hosting_company_metabox', 'hosting_reviews' );
}

add_action('init', 'create_hosting_reviews');
add_action( 'add_meta_boxes', 'vq_add_hosting_metaboxes' );
add_action( 'save_post_hosting_reviews', 'vq_save_hosting_review' );
