<?php


namespace App\PageBuilder\Addons\BrowseCategory;

use App\Category;
use App\PageBuilder\Fields\ColorPicker;
use App\PageBuilder\Fields\MultiSelect;
use App\PageBuilder\Fields\Number;
use App\PageBuilder\Fields\Select;
use App\PageBuilder\Fields\Slider;
use App\PageBuilder\Fields\Switcher;
use App\PageBuilder\Fields\Text;
use App\PageBuilder\Fields\Textarea;
use App\PageBuilder\Traits\LanguageFallbackForPageBuilder;

class BrowseCategoryOne extends \App\PageBuilder\PageBuilderBase
{
    use LanguageFallbackForPageBuilder;

    public function preview_image()
    {
        return 'home-page/browse_category.png';
    }

    public function admin_render()
    {
        $output = $this->admin_form_before();
        $output .= $this->admin_form_start();
        $output .= $this->default_fields();
        $widget_saved_values = $this->get_settings();


        $output .= Text::get([
            'name' => 'title',
            'label' => __('Title'),
            'value' => $widget_saved_values['title'] ?? null,
        ]);
        $output .= ColorPicker::get([
            'name' => 'title_text_color',
            'label' => __('Title Text Color'),
            'value' => $widget_saved_values['title_text_color'] ?? null,
            'info' => __('select color you want to show in frontend'),
        ]);
        $output .= Textarea::get([
            'name' => 'subtitle',
            'label' => __('Subtitle'),
            'value' => $widget_saved_values['subtitle'] ?? null,
        ]);

        $categories = Category::where('status', 1)->pluck('name', 'id')->toArray();
        $output .= MultiSelect::get([
            'name' => 'selected_categories',
            'label' => __('Select Categories'),
            'options' => $categories,
            'value' => $widget_saved_values['selected_categories'] ?? [],
            'info' => __('Select specific categories to display. Leave empty to show all categories based on other settings.'),
        ]);
        $output .= Select::get([
            'name' => 'order_by',
            'label' => __('Order By'),
            'options' => [
                'id' => __('ID'),
                'created_at' => __('Date'),
            ],
            'value' => $widget_saved_values['order_by'] ?? null,
            'info' => __('set order by')
        ]);
        $output .= Select::get([
            'name' => 'order',
            'label' => __('Order'),
            'options' => [
                'asc' => __('Accessing'),
                'desc' => __('Decreasing'),
            ],
            'value' => $widget_saved_values['order'] ?? null,
            'info' => __('set order')
        ]);
        $output .= Number::get([
            'name' => 'items',
            'label' => __('Items'),
            'value' => $widget_saved_values['items'] ?? null,
            'info' => __('enter how many item you want to show in frontend'),
        ]);

        $output .= Switcher::get([
            'name' => 'empty_category_show_hide',
            'label' => __('Category'),
            'value' => $widget_saved_values['empty_category_show_hide'] ?? null,
            'info' => __('Enable: The category will be displayed if it has service or not. Disable: The category will be displayed if it has service.'),
        ]);

        $output .= Slider::get([
            'name' => 'padding_top',
            'label' => __('Padding Top'),
            'value' => $widget_saved_values['padding_top'] ?? 260,
            'max' => 500,
        ]);

        $output .= Slider::get([
            'name' => 'padding_bottom',
            'label' => __('Padding Bottom'),
            'value' => $widget_saved_values['padding_bottom'] ?? 190,
            'max' => 500,
        ]);
        $output .= ColorPicker::get([
            'name' => 'section_bg',
            'label' => __('Background Color'),
            'value' => $widget_saved_values['section_bg'] ?? null,
            'info' => __('select color you want to show in frontend'),
        ]);

        $output .= $this->admin_form_submit_button();
        $output .= $this->admin_form_end();
        $output .= $this->admin_form_after();

        return $output;
    }
    

    public function frontend_render() : string
    {
        $settings = $this->get_settings();
        $title =$settings['title'];
        $title_text_color =$settings['title_text_color'];
        $explode = explode(" ",$title);
        $title_start = current($explode);
        $title_end = end($explode);
        $subtitle = $settings['subtitle'];
 
        $order_by =$settings['order_by'];
        $IDorDate =$settings['order'];
        $items =$settings['items'];

        $selected_categories = $settings['selected_categories'] ?? [];
        
        $padding_top = $settings['padding_top'];
        $padding_bottom = $settings['padding_bottom'];
        $section_bg = $settings['section_bg'];
        $empty_category =$settings['empty_category_show_hide'] ?? '';


        //static text helpers
        $static_text = static_text();

        // Query categories
        $query = Category::with('services')->where('status', 1);

        if (!empty($selected_categories)) {
            // Render only selected categories
            $query->whereIn('id', $selected_categories);
            $all_category = $query->withCount('services')
                ->orderBy('name', 'asc')
                ->take($items)
                ->get();
        } else {
            // Fallback to original logic
            if ($empty_category) {
                $all_category = $query->withCount('services')
                    ->orderByRaw('services_count > 0 DESC')
                    ->orderBy('name', 'asc')
                    ->take($items)
                    ->get();
            } else {
                $all_category = $query->whereHas('services')
                    ->withCount('services')
                    ->orderBy($order_by, $IDorDate)
                    ->take($items)
                    ->get();
            }
        }

        $route = route('service.list.category');
        $category_markup = '';
        foreach ($all_category as $cat){
            $name = $cat->name;
            $slug = $cat->slug;
            $icon = $cat->icon;
            $service_count = $cat->services->count();

 $category_markup.= <<<CATEGORY
<div class="single-category-item wow fadeInUp" data-wow-delay=".2s">
    <div class="single-category">
        <div class="icon">
           <i class="{$icon}"></i>
        </div>
        <div class="category-contents">
           <h4 class="category-title"> <a href="{$route}/{$slug}"> {$name} </a> </h4>
           <span class="category-para"> {$service_count}+ {$static_text['service']} </span>
        </div>
    </div>
</div>

CATEGORY;
        
}


return <<<HTML
<section class="category-area section-bg-1" data-padding-top="{$padding_top}" data-padding-bottom="{$padding_bottom}" style="background-color:{$section_bg}">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-xl-6 col-lg-7 col-md-10">
                <div class="section-title">
                    <h2 class="title"> {$title_start} <span style="color:{$title_text_color}"> {$title_end} </span> </h2>
                    <span class="section-para">{$subtitle}</span>
                </div>
            </div>
        </div>
        <div class="row margin-top-50">
            <div class="col-lg-12">
                <div class="category-slider dot-style-one">
                    {$category_markup}
                </div>
            </div>
        </div>
    </div>
</section>
    
HTML;

}

    public function addon_title()
    {
        return __('Browse Category: 01');
    }
}