<?php
/**
 * Created by PhpStorm.
 * User: Chubbard
 * Date: 10/12/23
 * Time: 2:17 PM
 */


$io_widget_cart = 0;

// The widget class
class Widget_TentCalculator extends WP_Widget {

    // Main constructor
    public function __construct()
    {
        parent::__construct(
            'Widget_TentCalculator',
            __('InflatableOffice Tent Calculator', 'text_domain'),
            array(
                'customize_selective_refresh' => true,
            )
        );
    }

    // The widget form (for the backend )
    public function form( $instance )
    {
        $items          = isset($instance['items']) ? $instance['items'] : array();
        $sidewalls      = isset($instance['sidewalls']) ? $instance['sidewalls'] : '';

        // Default selection for tent_sizes if not set
        $default_tent_sizes = array('10x10', '15x15'); // Add default sizes here
        $tent_sizes = isset($instance['tent_sizes']) ? $instance['tent_sizes'] : $default_tent_sizes;

        // Default selection for table_sizes if not set
        $default_table_sizes = array('8'); // Add default sizes here
        $table_sizes = isset($instance['table_sizes']) ? $instance['table_sizes'] : $default_table_sizes;

        //echo print_r($tent_sizes, true);

        // Default selection for eventTypes if not set
        $default_event_types = array('cocktail', 'Dinner'); // Add default event types here
        $eventTypes = isset($instance['eventTypes']) ? $instance['eventTypes'] : $default_event_types;
        ?>

        <label for="Sidwalls">Are Sidewalls for the tents available to rent?</label>
        <label for="<?php echo $this->get_field_id('sidewalls')?>"></label><input type="checkbox" id="<?php echo $this->get_field_id('sidewalls')?>" name="<?php echo $this->get_field_name('sidewalls')?>" value="Sidewalls"<?php checked($sidewalls, '1'); ?>>


        <div id="dropdownDiv">
            <label for="<?php echo $this->get_field_id('items'); ?>">Items in inventory with dimensions or space required defined in a * x * x * or * x * format</label> <a onclick="jQuery('#<?php echo $this->get_field_id('items'); ?>').val([]);" style="cursor:pointer">Clear</a>
            <select name="<?php echo $this->get_field_name('items'); ?>[]" id="<?php echo $this->get_field_id('items'); ?>" class="widefat" multiple style="height:200px">
                <?php
                $args = array('orderby' => 'name', 'order' => 'ASC', 'post_type' => 'page', 'posts_per_page' => -1);
                $loop = new WP_Query($args);
                $Dimensionspattern = '/^\d+(\')?\s*x\s*\d+(\")?\s*(x\s*\d+(\')?)?$/';
                $Footprintpattern = '/^\d+(\')?\s*x\s*\d+(\")?$/';
                while ( $loop->have_posts() ) : $loop->the_post();
                    //$options[$post->post_id] = array($post->post_title, 'text_domain');;
                    $key = get_the_id();
                    $name = get_the_title();
                    $content = get_the_content();
                    $loc1 = strpos($content, 'dimensions="') +strlen('dimensions="');
                    $loc3 = strpos($content, 'footprint="') + strlen('footprint="');
                    $dimensions = "";
                    $footprint = "";
                    $valueToUse = "";
                    if($loc1 && $loc1 <strlen($content)) {
                        $loc2 = strpos($content, '"', $loc1 + 1);
                        $dimensions = substr($content, $loc1 , $loc2 - $loc1 );
                    }
                    if($loc3 && $loc3 <strlen($content)) {
                        $loc4 = strpos($content, '"', $loc3 + 1);
                        $footprint = substr($content, $loc3, $loc4 - $loc3 );
                    }
                    $isFootprintValid = preg_match($Footprintpattern, trim($footprint));
                    $isDimensionsValid = preg_match($Dimensionspattern, trim($dimensions));
                    if ($isFootprintValid) {
                        $valueToUse = $footprint;
                    }
                    elseif ($isDimensionsValid) {
                        $valueToUse = $dimensions;
                    }
                    if (!empty($valueToUse)) {
                        $values = preg_split('/\s*x\s*/', $valueToUse);
                        $footprintArea = ((float)$values[0] + 0.5) * ((float)$values[1] + .5);
                        $footprintArea = ceil($footprintArea);
                        $valueToUse = $footprintArea;
                    }

                    if(strpos($content,'[sc :io_rental')!==FALSE) {
                        $select = in_array($key, $items);
                        if (!empty($valueToUse)) {
                            $selected = $select ? "selected" : "";
                            echo '<option value="' . esc_attr($key . "-" . $valueToUse) . '"  id="' . esc_attr($key) . '" ' . $selected . '>' . $name . '</option>';
                        }
                    }
                endwhile;
                ?>
            </select>
        </div>
        <div>
            <label for="<?php echo $this->get_field_id('tent_sizes'); ?>">Select Tent Sizes: These are the available tents to rent</label>
            <select name="<?php echo $this->get_field_name('tent_sizes'); ?>[]" id="<?php echo $this->get_field_id('tent_sizes'); ?>" class="widefat" multiple="multiple" size="8" style="height: 150px" >
                <option value="10x10"<?php echo in_array('10x10', $tent_sizes) ? 'selected' : ''; ?>>10x10</option>
                <option value="10x15"<?php echo in_array('10x15', $tent_sizes) ? 'selected' : ''; ?>>10x15</option>
                <option value="10x20"<?php echo in_array('10x20', $tent_sizes) ? 'selected' : ''; ?>>10x20</option>
                <option value="15x15"<?php echo in_array('15x15', $tent_sizes) ? 'selected' : ''; ?>>15x15</option>
                <option value="15x20"<?php echo in_array('15x20', $tent_sizes) ? 'selected' : ''; ?>>15x20</option>
                <option value="20x20"<?php echo in_array('20x20', $tent_sizes) ? 'selected' : ''; ?>>20x20</option>
                <option value="20x25"<?php echo in_array('20x25', $tent_sizes) ? 'selected' : ''; ?>>20x25</option>
                <option value="20x30"<?php echo in_array('20x30', $tent_sizes) ? 'selected' : ''; ?>>20x30</option>
                <option value="20x40"<?php echo in_array('20x40', $tent_sizes) ? 'selected' : ''; ?>>20x40</option>
                <option value="25x25"<?php echo in_array('25x25', $tent_sizes) ? 'selected' : ''; ?>>25x25</option>
                <option value="30x30"<?php echo in_array('30x30', $tent_sizes) ? 'selected' : ''; ?>>30x30</option>
                <option value="30x50"<?php echo in_array('30x50', $tent_sizes) ? 'selected' : ''; ?>>30x50</option>
                <option value="30x70"<?php echo in_array('30x70', $tent_sizes) ? 'selected' : ''; ?>>30x70</option>
                <option value="30x90"<?php echo in_array('30x90', $tent_sizes) ? 'selected' : ''; ?>>30x90</option>

                <option value="40x40"<?php echo in_array('40x40', $tent_sizes) ? 'selected' : ''; ?>>40x40</option>
                <option value="40x60"<?php echo in_array('40x60', $tent_sizes) ? 'selected' : ''; ?>>40x60</option>
                <option value="40x80"<?php echo in_array('40x80', $tent_sizes) ? 'selected' : ''; ?>>40x80</option>
                <option value="40x100"<?php echo in_array('40x100', $tent_sizes) ? 'selected' : ''; ?>>40x100</option>
                <option value="40x120"<?php echo in_array('40x120', $tent_sizes) ? 'selected' : ''; ?>>40x120</option>
                <option value="40x140"<?php echo in_array('40x140', $tent_sizes) ? 'selected' : ''; ?>>40x140</option>

                <option value="60x60"<?php echo in_array('60x60', $tent_sizes) ? 'selected' : ''; ?>>60x60</option>
                <option value="60x90"<?php echo in_array('60x90', $tent_sizes) ? 'selected' : ''; ?>>60x90</option>
            </select>
        </div>
        <div>
            <label for="<?php echo $this->get_field_id('table_sizes'); ?>">Select Table Sizes: These are the available Table sizes for layouts</label>
            <select name="<?php echo $this->get_field_name('table_sizes'); ?>[]" id="<?php echo $this->get_field_id('table_sizes'); ?>" class="widefat" multiple="multiple" size="8" style="height: 150px" >
                <option value="6x2.5"<?php echo in_array('6x2.5', $table_sizes) ? 'selected' : ''; ?>>6 Ft Rectangle</option>
                <option value="8x2.5"<?php echo in_array('8x2.5', $table_sizes) ? 'selected' : ''; ?>>8 Ft Rectangle</option>

            </select>
        </div>
        <div>
            <label for="<?php echo $this->get_field_id('eventTypes'); ?>">Select Event Types: These are the seating and table arrangements</label>
            <select name="<?php echo $this->get_field_name('eventTypes'); ?>[]" id="<?php echo $this->get_field_id('eventTypes'); ?>" class="widefat" multiple="multiple" size="5" style="height: 150px">
                <option value="cocktail" <?php echo in_array('cocktail', $eventTypes) ? 'selected' : ''; ?>>Standing Cocktail</option>
                <option value="Dinner" <?php echo in_array('Dinner', $eventTypes) ? 'selected' : ''; ?>>Dinner</option>
                <option value="ceremony" <?php echo in_array('ceremony', $eventTypes) ? 'selected' : ''; ?>>Ceremony Seating</option>
                <!-- Add more event types as needed -->
            </select>
        </div>
        </body>
        </html>
        <?php
        ;
    }

    // Update widget settings
    public function update( $new_instance, $old_instance ) {
        $instance = $new_instance;
        $instance['sidewalls'] = !empty($new_instance['sidewalls']) ? '1' : '';
        //echo print_r($instance, true);
        //echo print_r($new_instance, true);
        //echo print_r($old_instance, true);



        // Ensure 'tent_sizes' is always an array.
        //echo print_r($new_instance['tent_sizes'], true);
        $instance['tent_sizes'] = isset($new_instance['tent_sizes']) && is_array($new_instance['tent_sizes']) ? $new_instance['tent_sizes'] : [];
        //$instance['tent_sizes'] = $new_instance['tent_sizes'];
        //echo print_r($instance['tent_sizes'], true);

        // Ensure 'table_sizes' is always an array.
        $instance['table_sizes'] = isset($new_instance['table_sizes']) && is_array($new_instance['table_sizes']) ? $new_instance['table_sizes'] : [];


        // Ensure 'eventTypes' is always an array.
        $instance['eventTypes'] = isset($new_instance['eventTypes']) && is_array($new_instance['eventTypes']) ? $new_instance['eventTypes'] : [];

        // Ensure 'items' is always an array.
        $instance['items'] = isset($new_instance['items']) && is_array($new_instance['items']) ? $new_instance['items'] : [];

        // Process 'tent_sizes' array.
        foreach($instance['tent_sizes'] as $key => $value) {
            if ('' == trim($value)) {
                unset($instance['tent_sizes'][$key]);
            }
        }
        // Process 'table_sizes' array.
        foreach($instance['table_sizes'] as $key => $value) {
            if ('' == trim($value)) {
                unset($instance['table_sizes'][$key]);
            }
        }
        // Process 'eventTypes' array.
        foreach($instance['eventTypes'] as $key => $value) {
            if ('' == trim($value)) {
                unset($instance['eventTypes'][$key]);
            }
        }

        // Process 'items' array.
        foreach($instance['items'] as $key => $value) {
            if ('' == trim($value)) {
                unset($instance['items'][$key]);
            }
        }

        return $instance;
    }

    // Display the widget
    public function widget( $args, $instance )
    {




        $io_filter_dir = $_SERVER['SCRIPT_NAME'];
        $io_filter_server_name = $_SERVER['SERVER_NAME'];
        $io_filter_server_scheme = $_SERVER['REQUEST_SCHEME'];
        $url = $io_filter_server_scheme . "://" . $io_filter_server_name . str_replace("index.php", "wp-content/plugins/inflatableoffice-v2/TentCalcSubmit.php", $io_filter_dir);
        $default_event_types = array('cocktail', 'Dinner'); // Add your default event types here
        $eventTypes = !empty($instance['eventTypes']) ? $instance['eventTypes'] : $default_event_types;
        $items = isset($instance['items']) ? $instance['items'] : $args['items'];
        $items = empty($items) ? array(-1) : $items;
        $selected_items = isset($_POST['items']) ? $_POST['items'] : array();
        $selected_areas = array();
        foreach ($selected_items as $item) {
            $item_parts = explode('-', $item);
            if (count($item_parts) == 2) {
                $selected_areas[] = intval($item_parts[1]);
            }
        }
        $sidewalls = $instance['sidewalls'];
        // Ensure 'tent_sizes' is always an array.
        $tent_sizes = $instance['tent_sizes'];
        $TentAreaOptions = array();
        //echo print_r('hello');

        //echo print_r(gettype($tent_sizes), true);
        foreach ($tent_sizes as $size) {
            $TentSizes = explode('x', $size);
            if (count($TentSizes) == 2) {
                $TentArea = (float)$TentSizes[0] * (float)$TentSizes[1];
                $TentAreaOptions[$size] = $TentArea;
            }
        }
        $table_sizes = $instance['table_sizes'];
        $TableOptions = array();

        foreach ($table_sizes as $size2) {
            $TableSizes = explode('x', $size2);
            if (count($TableSizes) == 2) {
                $TableArea = (float)$TableSizes[0] * (float)$TableSizes[1];
                $TableOptions[$size2] = $TableArea;
            }
        }
        //echo print_r($TableOptions, true);


        //echo 'PHP version: ' . phpversion();


        $html = '<!DOCTYPE html>


    <html>
    <script>
        var tent_sizes = '. json_encode($TentAreaOptions) .';
        var table_Sizes = '. json_encode($TableOptions) .';
        var TentSubmitURL = "'. $url .'";
    </script>
    <style> 
            .grecaptcha-badge { visibility: hidden; }

.search-submit{display:none;}

.cartInfo{
	display:none !important;
}
.io-footer-link a {
color: var(--e-global-color-accent, orange);
}

.catDescriptionIO.catDescriptionIO_small.elementor-widget-text-editor {
    padding: 10px;
    font-size: small;
    text-align: left;
}

.elementor-widget-wp-widget-widget_tentcalculator{
	font-family:var(--e-global-typography-text-font-family);	
	min-height:50vh;
}

.elementor-widget-wp-widget-widget_tentcalculator .step{
	border-radius:0px !important;
}

#stepProgress1 {
	border-bottom-left-radius:5px !important;
	border-top-left-radius:5px !important;
}

#stepProgress6 {
	border-bottom-right-radius:5px !important;
	border-top-right-radius:5px !important;
}

.elementor-widget-wp-widget-widget_tentcalculator .input-container{
	background:#e5e5e8;
	width:50%;
	margin:0 auto;
	padding:20px;
	margin-top:30px;
	border-radius:10px;
}

.elementor-widget-wp-widget-widget_tentcalculator .input-container h2{
	margin-top:0
}

.elementor-widget-wp-widget-widget_tentcalculator .input-container input{
	margin-top:10px;
}

.elementor-widget-wp-widget-widget_tentcalculator .input-container button{
	padding:10px 30px;
	width:49%;
	border: none;
	background:#A3D7A7;
	cursor:pointer;
}

.elementor-widget-wp-widget-widget_tentcalculator .input-container button:first-of-type{	
	background:#4CAF50;
	color:white;
}

.elementor-widget-wp-widget-widget_tentcalculator .input-container > * {
	text-align:center;
}

.elementor-widget-wp-widget-widget_tentcalculator #conditionalInput{
	margin-top:20px;
}

.elementor-widget-wp-widget-widget_tentcalculator #conditionalInput input{
	margin-top:20px;
}

.elementor-widget-wp-widget-widget_tentcalculator input, 
.elementor-widget-wp-widget-widget_tentcalculator select{
	width:100%;
	padding:10px;
	margin-bottom:20px;
	border:1px solid #d3d3d3;	
	border-radius:5px;
}
#guest-form #resultDisplay {
    display: none;
}

#resultDisplay{
	width:50%;
	margin:0 auto;
	text-align:center;
	padding:20px;
	font-size:20px;
	background:#E5E5E8;
	margin-top:-13px;
	border-radius:10px;
}

@media(max-width:700px){
	
	.elementor-widget-wp-widget-widget_tentcalculator .input-container{width:95%}
	.progress-tracker{
		flex-wrap:wrap;
	}
	.progress-tracker .step{
		width:50%;
		font-size:14px;
	}
	.elementor-widget-wp-widget-widget_tentcalculator .input-container h2{
	font-size:18px;
}
}



      
            #weatherConsiderations {
                margin-left: 10px;
            }
            .checkbox {
                display: flex;
            }
            .checkbox input {
                width: unset;
                margin-right: 10px;
                border: 1px solid #e8e8e8;
            }
            .event-time {
                display: flex;
            }
            .welcome-container {
                text-align: center;
            }
            h1 {
                color: #333;
            }
            p {
                color: #666;
            }
            #start-button, .step-button {
                background-color: var(--e-global-color-primary);
                /* change this to match your brand color */
                border: none;
                color: white;
                padding: 15px 32px;
                text-align: center;
                text-decoration: none;
                display: inline-block;
                font-size: 16px;
                margin: 4px 2px;
                cursor: pointer;
            }
            
           .progress-tracker {
    display: flex;
    justify-content: space-between;
    list-style-type: none;
    margin: 0;
    padding: 0;
}
.step {
    width: 25%; /* Adjust based on the number of steps */
    padding: 10px;
    text-align: center;
    background-color: #efefef; /* Non-active step */
    border-radius: 5px;
}
.step.active {
    background-color: #4CAF50; /* Active step */
    color: white;
}
.step.completed {
    background-color: #a4d7a7; /* Completed step */
}
           
                 
        </style>
        
    </head>
    <div id="progressTracker" class="progress-tracker" style="display: none;">
        <div class="progress-tracker">
            <div id="stepProgress1" class="step">Step 1: Number of Guests</div>
            <div id="stepProgress2" class="step">Step 2: Type of Event</div>
            <div id="stepProgress3" class="step">Step 3: Additional Features</div>
            <div id="stepProgress4" class="step">Step 4: Event Duration</div>
            <div id="stepProgress5" class="step">Step 5: Weather Considerations</div>
            <div id="stepProgress6" class="step">Step 6: Get Results</div>
            <!-- Add more steps as needed -->
        </div>
    </div>
    
    <body>
        <form id="guest-form" name="guest-form">
         <div class="welcome-container steps" id="step_1">
           <h1>Welcome to the Tent Size Calculator!</h1>
           <p>Let us help you figure out the perfect tent size for your event.</p>           
           <button id="start-button" type="button" onclick="nextStep(2);">Start Calculating</button>
         </div>
         <div class="input-container steps" id="step_2" style="display:none;">
           <h2>Number of Guests</h2>
             <label for="numberOfGuests">Enter the number of guests:</label><br>
             <input type="number" id="numberOfGuests" name="numberOfGuests" min="1" required>      
             <button  type="button" onclick="nextStep(3);">Next</button>
             <button  type="button" onclick="nextStep(1);">Back</button>
         </div>
         <div class="input-container steps" id="step_3" style="display:none;">
           <h2>Type of Event</h2>
           <select id="eventType" name="eventType" onchange="addConditionalInput();">
               <option value="Default">Choose an Event Type</option>';
        foreach ($eventTypes as $eventType) {
            $selected = in_array($eventType, $eventTypes) ? ' selected' : '';
            $optionText = '';
            switch ($eventType) {
                case 'cocktail':
                    $optionText = 'Standing Cocktail';
                    break;
                case 'Dinner':
                    $optionText = 'Seated Dinner';
                    break;
                case 'ceremony':
                    $optionText = 'Ceremony Seating';
                    break;
            }
            $html .= '<option value="' . $eventType . '"' . $selected . '>' . $optionText . '</option>';
        }

        $html .='  </select>

               
           <button  type="button" onclick="nextStep(4);">Next</button>
           <button  type="button" onclick="nextStep(2);">Back</button>
         </div>
            <div class="input-container steps" id="step_4" style="display:none;">
              <h2>Additional Features</h2>';

        if (!empty($items) && $items[0] != -1) {
            $html .= '<div class="items-container"><ul>';
            foreach ($items as $item) {
                $item_details = get_post($item);

                if ($item_details) {
                    $item_title = esc_html($item_details->post_title);
                    $html .= '<div class="checkbox">
                                        <input type="checkbox" id="item_' . esc_attr($item) . '" name="items[]" value="' . esc_attr($item) . '">
                                        <label for="item_' . esc_attr($item) . '">' . $item_title . '</label>
                                        </div>';
                }
            }
            $html .= '</ul></div>';

        }
        $html .= ' <button  type="button" onclick="nextStep(6);">Next</button>
                   <button  type="button" onclick="nextStep(3);">Back</button>';

        $html .= '  </div>
             
             <div class="input-container steps" id="step_5" style="display:none;">
           <h2>Event Duration</h2>
             
             <select id="duration-type" name="duration-type">
               <option value="hours">Hours</option>
               <option value="days">Days</option>
             </select>';
        $nextstep = empty($sidewalls) ? 7 : 6;
        $html .= '<button  type="button" onclick="nextStep(' . $nextstep . ')">Next</button>
                  <button  type="button" onclick="nextStep(4);">Back</button>
                  </div>';

        if (!empty($sidewalls)) {
            $html .= '<div class="input-container steps" id = "step_6" style = "display:none;" >
                      <h2 > Weather Considerations </h2 >
                      <label for="weatherConsiderations" > Side walls needed ?</label >
                      <input type = "checkbox" id = "weatherConsiderations" name = "weatherConsiderations" >
                      <button  type = "button" onclick = "nextStep(7);" > Next</button >
                      <button  type = "button" onclick = "nextStep(4);" > Back</button >
                      </div >';
        }

        $html .= '
         <div class="input-container steps" id="step_7" style="display:none;">
             <h2>Before displaying your results please enter your email below</h2>
             <input type="email" id="userEmail" name="userEmail" placeholder="Enter your email" required>
             <button id= "calculateBtn" type="button" onclick="CalculateButton();">Get Results</button>
             <button id="resetBtn" type="button" onclick="resetCalculator();">Reset Calculator</button>
             <div id="result" style="display:none;"></div>
         </div>
            <div id="resultDisplay">
         
            </div> <!-- This is where the tent size result will be displayed -->           
    
            
            
        </form>
        

  </body>


</html>';
        echo $html;
    }
}

