<?php

class UtilHTML
{
    public static function create_filter_date($id, $fieldName, $fieldValue, $label, $class_div, $class_input)
    {
        if (!isset($id)) { $id = $fieldName; }

        $html = "";
        $html .= "<div class='{$class_div}'>";
        $html .=    "<div class='filter-group form-group'>";
        $html .=        "<label for='{$id}'>{$label}</label>";
        $html .=        "<input 
                            type='text' 
                            id='{$id}' 
                            name='{$fieldName}' 
                            value='".UtilRender::escapeHtml($fieldValue)."'
                            style='background-color: white;'
                            class='filter-date form-control form-control-sm {$class_input}' >";
        $html .=    "</div>";
        $html .=  "</div>";

        return $html;
    }

    public static function create_filter_datetime($id, $fieldName, $fieldValue, $label, $class_div, $class_input)
    {
        if (!isset($id)) { $id = $fieldName; }

        $html = "";
        $html .= "<div class='{$class_div}'>";
        $html .=    "<div class='filter-group form-group'>";
        $html .=        "<label for='{$id}'>{$label}</label>";
        $html .=        "<input 
                            type='text' 
                            id='{$id}' 
                            name='{$fieldName}' 
                            class='form-control form-control-sm {$class_input} '
                            value='".UtilRender::escapeHtml($fieldValue).
                        "'>";
        $html .=    "</div>";
        $html .=  "</div>";

        return $html;
    }

    public static function create_filter_search($id, $fieldName, $fieldValue, $label, $class_div, $class_input)
    {
        if (!isset($id)) { $id = $fieldName; }
    
        $html = "";
        $html .= "<div class='{$class_div}'>";
        $html .=    "<div class='filter-group form-group'>";
        $html .=        "<label for='{$id}'>{$label}</label>";
        $html .=        "<div class='input-group'>";
        $html .=        "<input type='text'
                                id='{$id}' 
                                name='{$fieldName}' 
                                class='form-control form-control-sm fa fa-search {$class_input}' 
                                placeholder='Search...'
                                value='".UtilRender::escapeHtml($fieldValue)."' >";
                        $html .=        "</div>";
        $html .=    "</div>";
        $html .=  "</div>";
        return $html;
    }



    public static function create_filter_select($id, $name, $label, $options, $optionColumnSelected, $optionColumn, $optionColumnText, $class_div, $class_input, $optionAll=true)
    {
        if (!isset($id)) { $id = $name; }

        $html = "";
        $html .= "<div class='{$class_div}'>";
        $html .=    "<div class='filter-group form-group'>";
        $html .=        "<label for='{$id}'>{$label}</label>";
        $html .=        "<select 
                            id='{$id}'
                            name='{$name}' 
                            class='searchable-select form-control form-control-sm {$class_input}' 
                            >";
        if ($optionAll)
        {
            $html .=            "<option value='none' selected>"."All"."</option>"; 
        }

        foreach ($options as $option)
        {
            $selected = ($option[$optionColumn] === $optionColumnSelected) ? " selected" : "";
            $html .=     "<option value='".UtilRender::escapeHtml($option[$optionColumn])."' {$selected}>".UtilRender::escapeHtml($option[$optionColumnText])."</option>";
        }
        $html .=         "</select>";
        $html .=    "</div>";
        $html .=  "</div>";
        
        return $html;
    }    


public function create_filter_checkbox($name, $id, $label, $options, $selectedValues, $valueKey = 'value', $textKey = 'text', $colClass = 'col-sm-4', $filterClass = '', $columns = 2)
{
    // Si selectedValues es null, inicializamos como array vacío
//    $selectedValues = $selectedValues ?: array();
    
    // Si selectedValues está vacío, seleccionar todos por defecto
    $allValues = array();
    foreach ($options as $option) {
        $allValues[] = $option[$valueKey];
    }    
    $selectedValues = !empty($selectedValues) ? $selectedValues : $allValues;

    $html = "<div class='$colClass $filterClass'>";
    $html .= "<label class='form-label fw-bold'>$label</label>";
    $html .= "<div class='checkbox-group border rounded p-3 bg-light' style='max-height: 200px; overflow-y: auto;'>";
    
    // Dividir las opciones en columnas
    $chunkSize = ceil(count($options) / $columns);
    $chunks = array_chunk($options, $chunkSize);
    
    $html .= "<div class='row'>";
    
    foreach ($chunks as $columnOptions) {
        $html .= "<div class='col'>";
        
        foreach ($columnOptions as $option) {
            $value = $option[$valueKey];
            $text = $option[$textKey];
            $isChecked = in_array($value, $selectedValues) ? 'checked' : '';
            
            $html .= "<div class='form-check'>";
//            $html .= "<input class='form-check-input crane-checkbox' type='checkbox' name='{$name}[]' id='{$id}_{$value}' value='{$value}' $isChecked onchange='handleCraneSelection()'>";
            $html .= "<input class='form-check-input crane-checkbox' type='checkbox' name='{$name}[]' id='{$id}_{$value}' value='{$value}' $isChecked>";
            $html .= "<label class='form-check-label' for='{$id}_{$value}'>{$text}</label>";
            $html .= "</div>";
        }
        
        $html .= "</div>"; // cierra col
    }
    
    $html .= "</div>"; // cierra row
    $html .= "</div>"; // cierra checkbox-group
    
    // Botones de selección rápida
    $html .= "<div class='mt-2'>";
    $html .= "<button type='button' class='btn btn-sm btn-outline-primary me-1' onclick='selectAllCranes()'>Select All</button>";
    $html .= "<button type='button' class='btn btn-sm btn-outline-secondary' onclick='deselectAllCranes()'>Deselect All</button>";
    $html .= "</div>";
    
    $html .= "</div>"; // cierra colClass
    
    return $html;
}    



    public static function create_boolean($name, $id, $label, $value, $colClass = '', $filterClass = '')
    {
        // Convertir el valor a booleano (0/1 o true/false)
        $isChecked = filter_var($value, FILTER_VALIDATE_BOOLEAN);
    
        $html = "<div class='$colClass $filterClass'>";
        $html .= "<div class='form-check form-switch'>";
        $html .= "<input class='form-check-input' type='checkbox' name='{$name}' id='$id' value='1' " . ($isChecked ? 'checked' : '') . ">";
        $html .= "<label class='form-check-label fw-bold' for='$id'>$label</label>";
        $html .= "</div>"; // cierra form-switch
        // Input hidden con el mismo nombre pero valor 0 (solo se enviará si el checkbox no está marcado)
        $html .= "<input type='hidden' name='{$name}' value='0'>";
        $html .= "</div>"; // cierra colClass
        
        return $html;
    }










    public static function create_td($value, $class, $style='')
    {
        $classHTML = "";
        $styleHTML = "";
        if (!empty($class)) {$classHTML = " class={$class}"; }
        if (!empty($style)) {$styleHTML = " style={$style}" ; }

        $html = "<td $classHTML $styleHTML>" .UtilRender::escapeHtml($value)."</td>";
        return $html;
    }    



public static function create_boolean_td($value, $colClass = '', $style = 'text-align: center; vertical-align: middle;')
{
    // Convertir el valor a booleano
    $isChecked = filter_var($value, FILTER_VALIDATE_BOOLEAN);
    
    $html = "<td class='$colClass align-middle' style='$style'>";
    $html .= "<div class='d-flex justify-content-center align-items-center'>";
    
    // Div personalizado - solo el cuadro sin checkmark
    $html .= "<div style='";
    $html .= "width: 20px; ";
    $html .= "height: 20px; ";
    $html .= "border: 2px solid #000000; ";
    $html .= "background-color: " . ($isChecked ? "#5c5c5cff" : "#ffffff") . "; ";
    $html .= "display: inline-block; ";
    $html .= "cursor: default;";
    $html .= "'>";
    $html .= "</div>"; // Cierra el div personalizado
    
    $html .= "</div>"; // Cierra el div flex
    $html .= "</td>";
    
    return $html;
}



    // antiguo
    public static function create_th_sortable( $sort, $columName, $columLabel, $queryString, $class, $style='')
    {
        $icon            = $sort['direction'] === 'ASC' ? '▲' : '▼';
        $sortIcon        = $sort['column'] == $columName ? " $icon" : '';
        $sortDirection   = $sort['column'] == $columName && $sort['direction'] == 'ASC' ? 'DESC' : 'ASC';

        $html = "<th class='$class' style='$style'>";
//        $html .= UtilRender::escapeHtml($value);
        $html .= "<a href='index.php?".$queryString."&sort_column=$columName&sort_direction=$sortDirection'>$columLabel $sortIcon </a>";
        $html .="</th>";
        return $html;
    }    

    
    // nuevo con onclick event
    public static function create_columnSortable ($sort, $columName, $columLabel, $class, $style, $jsFunction)
    {
        $ico_empty = '';
        $ico_asc = '▲';
        $ico_desc = '▼';
        $sortDirection = 'ASC';
        $sortIcon = '';

        
        if ( !isset($sort['column']) || $sort['column']  != $columName ) {
             $sortIcon = $ico_empty; 
             $sortDirection = 'ASC';
        }
        else if ( $sort['column'] == $columName && ($sort['direction'] === 'ASC' || $sort['direction']=== '') ) { 
            $sortIcon = $ico_asc; 
            $sortDirection = 'DESC';
        }
        else if ( $sort['column'] == $columName ) { 
            $sortIcon = $ico_desc;
            $sortDirection = 'ASC';
        }

        $classHTML = "";
        $styleHTML = "";
        if (!empty($class)) {$classHTML = " class={$class}"; }
        if (!empty($style)) {$styleHTML = " style={$style}" ; }

        $html = "<th $classHTML $styleHTML>";
//        $html .= "<a href='' onclick=\"{$jsFunction}('$columName', '$sortDirection')\"> $columLabel $sortIcon </a>";        
        $html .= "<button type='button' onclick=\"{$jsFunction}('$columName', '$sortDirection')\" class='btn btn-link'> $columLabel $sortIcon </button>";                
        $html .= "</th>";
        return $html;
    }


    public static function create_button_clearFilters($action, $class_div)
    {
        $html = "";
        $html .= "<div class='{$class_div}'>";
        $html .=   "<div class='form-group filter-group '>";        
        $html .=       "<button id='clearFilters' class='btn btn-primary btn-create' action='{$action}'> Clear Filters </button>";
        $html .=    "</div>"; 
        $html .= "</div>";
        return $html;
    }    








    public static function create_button_exportExcel($idTable, $class_div)
    {
        $html = "";
        $html .= "<div class='{$class_div}'>";
        $html .=   "<div class='form-group filter-group '>";        
        $html .=       "<button id='exportExcel' idtable='{$idTable}' class='btn btn-primary btn-sm'> Export Excel </button>";
        $html .=    "</div>"; 
        $html .= "</div>";
        return $html;
    }    

    public static function create_button_exportJson($action, $class_div )
    {
        $html = "";
        $html .= "<div class='{$class_div}'>";
        $html .=   "<div class='form-group filter-group '>";        
        $html .=       "<button id='exportJson' action='{$action}' class='btn btn-primary btn-sm'> Export Json </button>";
        $html .=    "</div>"; 
        $html .= "</div>";
        return $html;
    }    


    public static function createButton($buttonText, $onClickFunction, $params = []) {
        // Codifica los parámetros en formato JSON para que JavaScript los interprete correctamente
        $encodedParams = json_encode($params);
        return "
            <div>
                <div class='form-group filter-group'>
                    <button class='btn btn-sm btn-primary btn-create' type='button' onclick='{$onClickFunction}({$encodedParams})'>
                        {$buttonText}
                    </button>
                </div>
            </div>
        ";
    }    
}
?>