<?php
if (!defined('ABSPATH'))
    exit; // Exit if accessed directly
if (!is_user_logged_in()) {
    header('Location:' . site_url('/bits-login'));
}
$pro_enabled = dspp_check_api_connection_settings();
$site_url = site_url();
$user_id_wp = get_current_user_id();
$custom_website_data = get_user_meta($user_id_wp, 'custom_website_data', true);
$decoded_array = json_decode($custom_website_data, true);
$cart_data = isset($decoded_array['custom_website_data_' . $user_id_wp]) ? $decoded_array['custom_website_data_' . $user_id_wp] : array();
$item_cout = 0;
foreach ($cart_data as $key => $value) {
    if (is_array($value)) {
        $item_cout++;
    }
}
?>
<div class="container">
    <div class="row">
        <div class="col-sm-6"><h2 class="page-title"><?php esc_html_e('Services', 'digital-service-provider-crm'); ?></h2></div>
        <div class="col-sm-6">
            <a class="btn btn-primary float-end view_cart_button" href="<?php echo esc_url(site_url("/bits-cart")); ?>">
                <?php esc_html_e('View Cart | ', 'digital-service-provider-crm'); ?>
                <span id="cartCount"><?php echo esc_html($item_cout); ?></span>
                <span class="spinner-border spinner-border-sm text-light d-none ms-2" role="status" aria-hidden="true"></span>
            </a>

        </div>
    </div>
    <div class="view-cart alert alert-success" style="display:none;"><?php esc_html_e('Items added to cart successfully!', 'digital-service-provider-crm'); ?></div>
    <?php
    $services_list = dspp_get_all_services_cpt();
    foreach ($services_list as $index => $service):
        if ($index % 3 === 0):
            ?>
            <div class="row mb-4">
                <?php
            endif;
            $post_id = $service->ID;
            $service_price = get_post_meta($post_id, '_dspp_single_price', true);
            $service_type = get_post_meta($post_id, '_dspp_service_type', true);
            $numericString = preg_replace("/[^0-9.]/", "", $service_price);
            $service_price_int = floatval($numericString);
//            print_r($service_price_int);
//            exit;
            ?>
            <div class="col-sm-4">
                <div class="card">
                    <input type="hidden" name="service_id" value="<?php echo esc_attr($post_id); ?>">
                    <div class="card-body">
                        <h2 class="card-title"><?php echo esc_html($service->post_title); ?></h2>
                        <p class="card-text"><?php echo esc_html($service->post_content); ?></p>
                        <?php
                        if ($service_type === 'variable'):
                            $variations = get_post_meta($post_id, '_dspp_variations', true);
                            $attributes_raw = get_post_meta($post_id, '_dspp_attributes', true);

                            $attributes = [];
                            foreach ($attributes_raw as $attr) {
                                $attr_name = sanitize_title($attr['name']);
                                $attributes[$attr_name] = $attr['values'];
                            }

                            $default_variation = $variations[0] ?? [];
                            $default_price = $default_variation['price'] ?? 0;
                            ?>

                            <div class="dspp-attributes" data-post-id="<?php echo esc_attr($post_id); ?>">
                                <?php foreach ($attributes as $key => $values): ?>
                                    <select class="form-select attribute-dropdown mb-2" data-attribute="<?php echo esc_attr($key); ?>">
                                        <option value="">Choose <?php echo ucfirst($key); ?></option>
                                        <?php foreach ($values as $value): ?>
                                            <option value="<?php echo esc_attr($value); ?>"><?php echo esc_html($value); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                <?php endforeach; ?>
                            </div>
                        </div> <!-- /.card-body -->

                        <div class="card-footer">
                            <div class="d-flex align-items-center">
                                <div class="mr-2 small text-muted flex-fill price-display" data-price="<?php echo esc_attr($default_price); ?>">
                                    <strong>$<span class="price-value"><?php echo esc_html($default_price); ?></span></strong>
                                </div>
                                <div class="buttons">
                                    <button
                                        id="actionButton_<?php echo esc_attr($post_id); ?>"
                                        class="btncart btn btn-outline-primary ml-auto"
                                        data-post-id="<?php echo esc_attr($post_id); ?>"
                                        data-variation-id="0"
                                        data-site="<?php echo esc_attr($service->post_title); ?>"
                                        data-price="<?php echo esc_attr($default_price); ?>"
                                        data-user-id="<?php echo esc_attr(get_current_user_id()); ?>"
                                        data-variation-index="0"
                                        >
                                        <span class="icon-wrapper">
                                            <i class="fa fa-cart-plus fa-1x greencart" aria-hidden="true"></i>
                                            <span class="spinner-border spinner-border-sm text-primary d-none" role="status" aria-hidden="true"></span>
                                        </span>
                                        <span class="btn-label">
                                            <?php esc_html_e(' Add to cart', 'digital-service-provider-crm'); ?>
                                        </span>
                                    </button>
                                </div>
                            </div>
                            <script>
                                document.addEventListener('DOMContentLoaded', function () {
                                    const card = document.getElementById('actionButton_<?php echo esc_attr($post_id); ?>').closest('.card');
                                    const selects = card.querySelectorAll('.attribute-dropdown');
                                    const priceDisplay = card.querySelector('.price-value');
                                    const addToCartBtn = card.querySelector('.btncart');

                                    const variations = <?php echo json_encode($variations); ?>;

                                    function getSelectedAttributes() {
                                        const selected = {};
                                        selects.forEach(select => {
                                            const key = select.dataset.attribute.toLowerCase().trim();
                                            const value = select.value.trim();
                                            if (value)
                                                selected[key] = value;
                                        });
                                        return selected;
                                    }

                                    function normalizeAttributes(attrs) {
                                        const normalized = {};
                                        for (let key in attrs) {
                                            normalized[key.toLowerCase().trim()] = String(attrs[key]).trim();
                                        }
                                        return normalized;
                                    }

                                    function attributesMatch(selected, variationAttrs) {
                                        const vAttrs = normalizeAttributes(variationAttrs);
                                        const sKeys = Object.keys(selected);
                                        const vKeys = Object.keys(vAttrs);
                                        if (sKeys.length !== vKeys.length)
                                            return false;
                                        return sKeys.every(key => vAttrs[key] === selected[key]);
                                    }

                                    selects.forEach(select => {
                                        select.addEventListener('change', () => {
                                            const selected = getSelectedAttributes();
                                            if (Object.keys(selected).length === selects.length) {
                                                const match = variations.find(v => attributesMatch(selected, v.attributes));
                                                if (match) {
                                                    const index = variations.indexOf(match);
                                                    priceDisplay.textContent = match.price;
                                                    addToCartBtn.dataset.price = match.price;
                                                    addToCartBtn.dataset.variationIndex = index;
                                                    addToCartBtn.dataset.variationId = index;
                                                } else {
                                                    priceDisplay.textContent = 'N/A';
                                                    addToCartBtn.dataset.price = 0;
                                                }
                                            }
                                        });
                                    });
                                });
                            </script>
                        </div>
                    <?php else: ?>
                    </div> <!-- /.card-body -->
                    <div class="card-footer">
                        <div class="d-flex align-items-center">
                            <div class="mr-2 small text-muted flex-fill" data-price="<?php echo esc_attr($service_price); ?>">
                                <strong>$<?php echo esc_html($service_price); ?></strong>
                            </div>
                            <div class="buttons">
                                <button
                                    data-post-id="<?php echo esc_attr($post_id); ?>"
                                    data-variation-id="0"
                                    data-site="<?php echo esc_attr($service->post_title); ?>"
                                    data-price="<?php echo esc_attr($service_price_int); ?>"
                                    data-user-id="<?php echo esc_attr(get_current_user_id()); ?>"
                                    class="btncart btn btn-outline-primary ml-auto"
                                    >
                                    <i class="fa fa-cart-plus fa-1x greencart" aria-hidden="true"></i>
                                    <span class="spinner-border spinner-border-sm text-success d-none" role="status" aria-hidden="true"></span>
                                    <?php esc_html_e(' Add to cart', 'digital-service-provider-crm'); ?>
                                </button>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div> <!-- /.card -->
        </div>
        <?php if ($index % 3 === 2 || $index === count($services_list) - 1): ?>
        </div> <!-- /.row -->
    <?php endif; ?>
<?php endforeach; ?>
<script>
    jQuery(document).ready(function ($) {
        $('#variationSelect').on('change', function () {
            var selectedOption = $(this).find('option:selected');
            var price = selectedOption.val();
            var index = selectedOption.data('index');
            $('#actionButton')
                    .attr('data-price', price)
                    .attr('data-variation-id', index);
        });
    });
</script>