<?php
/**
 * Template part for displaying front-page box section
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/
 *
 * @package Suit Blog
 */

class Front_Page_Boxes {
    /**
     * Format the image properly for use in img src attribute.
     *
     * @param int|string $image (required) The image ID or URL.
     *
     * @since 1.5.8
     * @access public
     * @return string
     */
    public function generate_image_url($image)
    {
        if (is_numeric($image)) {
            $URL = wp_get_attachment_image_src($image);
            $URL = $URL[0]; // Return the attachment URL.
        } else {
            $URL = $image;
        }
        return $URL;
    }
}

$frontPageBoxes = new Front_Page_Boxes();

$enable = false;
if ((is_front_page() || is_home()) && get_theme_mod('box_home_page_enable', true)) {
    $enable = true;
} elseif (is_page() && get_theme_mod('box_single_pages_enable', false)) {
    $enable = true;
} elseif (is_single() && get_theme_mod('box_single_posts_enable', false)) {
    $enable = true;
}

$boxes = get_theme_mod('boxes_options', []);
$box_heading = get_theme_mod('frontpage_box_heading');

if ($enable) :
    $boxCount = count($boxes);
?>
    <section class="box-section">
        <?php if (!empty($box_heading)) : ?>
		<div class="box-header">
            <h1><?php echo esc_html($box_heading); ?></h1>
        </div>
		<?php endif; ?>
        <div class="row boxes">
            <?php foreach ($boxes as $box) : ?>
                <div class="col-md-<?php echo 12 / $boxCount; ?>">
                        <?php if ($box['url']) : ?>
                            <a target="_self" href="<?php echo esc_url($box['url']); ?>" target="_blank">
                        <?php endif; ?>

                        <?php if (!empty($box['image'])) : ?>
                            <img src="<?php echo esc_url($frontPageBoxes->generate_image_url($box['image'])); ?>" alt="<?php echo esc_attr($box['title']); ?>">
                        <?php endif; ?>

                        <?php if (!empty($box['icon'])) : ?>
                            <i class="fas <?php echo esc_attr($box['icon']); ?>" style="<?php echo !empty($box['icon_color']) ? 'color:' . esc_attr($box['icon_color']) . ';' : ''; ?>"></i>
                        <?php endif; ?>

                        <?php if ($box['url']) : ?>
                            </a>
                        <?php endif; ?>

                        <?php if (!empty($box['title'])) : ?>
                            <h2><?php echo esc_html($box['title']); ?></h2>
                        <?php endif; ?>

                        <?php if (!empty($box['text'])) : ?>
                            <p><?php echo esc_html($box['text']); ?></p>
                        <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </section><!-- .box-section -->
<?php endif; ?>
