<?php
/**
 * Base URL Configuration
 * Change this to your local development URL
 */
define('BASE_PATH', __DIR__);
define('BASE_URL', 'http://zibot.store');
define('BASE_URL_HTTPS', 'https://zibot.store');
// Database Configuration
define('DB_HOST', 'localhost');
define('DB_USER', 'rockbvxw_crest');
define('DB_PASS', 'rockbvxw_crest');
define('DB_NAME', 'rockbvxw_crest');

// Helper function to get base URL
function get_base_url()
{
    return BASE_URL;
}

// Database connection function
function get_db_connection()
{
    static $conn = null;
    if ($conn === null) {
        $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        $conn->set_charset("utf8");
    }
    return $conn;
}

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Helper function to get phone number from database
function get_phone_number()
{
    static $phone = null;
    if ($phone === null) {
        $conn = get_db_connection();
        $result = $conn->query("SELECT setting_value FROM website_settings WHERE setting_key = 'phone_number' LIMIT 1");
        if ($result && $row = $result->fetch_assoc()) {
            $raw_phone = trim($row['setting_value']);
            $phone = !empty($raw_phone) ? $raw_phone : '';
        } else {
            $phone = '';
        }
    }
    // Format phone number if it exists (format: (XXX) XXX-XXXX)
    if (!empty($phone) && $phone !== '') {
        $digits = preg_replace('/[^0-9]/', '', $phone);
        if (strlen($digits) == 10) {
            return '(' . substr($digits, 0, 3) . ') ' . substr($digits, 3, 3) . '-' . substr($digits, 6, 4);
        }
        return $phone;
    }
    return '';
}

// Helper function to get phone number for tel: links
function get_phone_number_tel()
{
    $phone = get_phone_number();
    if (empty($phone)) {
        return '';
    }
    return preg_replace('/[^0-9+]/', '', $phone);
}

// Helper function to get email from database
function get_email()
{
    static $email = null;
    if ($email === null) {
        $conn = get_db_connection();
        if ($conn && !$conn->connect_error) {
            $result = $conn->query("SELECT setting_value FROM website_settings WHERE setting_key = 'email' LIMIT 1");
            if ($result && $row = $result->fetch_assoc()) {
                $email = trim($row['setting_value']);
            } else {
                $email = '';
            }
        } else {
            $email = '';
        }
    }
    return $email;
}

// Helper function to get site color from database
function get_site_color()
{
    static $color = null;
    if ($color === null) {
        $conn = get_db_connection();
        if ($conn && !$conn->connect_error) {
            $result = $conn->query("SELECT setting_value FROM website_settings WHERE setting_key = 'site_color' LIMIT 1");
            if ($result && $row = $result->fetch_assoc()) {
                $color = trim($row['setting_value']);
            } else {
                $color = '#F49321'; // Default fallback
            }
        } else {
            $color = '#F49321'; // Default fallback
        }
    }
    return $color;
}

// Helper function to get color value from database
function get_color_value($key, $default)
{
    static $colors = [];
    if (!isset($colors[$key])) {
        $conn = get_db_connection();
        if ($conn && !$conn->connect_error) {
            $result = $conn->query("SELECT setting_value FROM website_settings WHERE setting_key = '$key' LIMIT 1");
            if ($result && $row = $result->fetch_assoc()) {
                $colors[$key] = trim($row['setting_value']);
            } else {
                $colors[$key] = $default;
            }
        } else {
            $colors[$key] = $default;
        }
    }
    return $colors[$key];
}

// Color helper functions
function get_primary_color()
{
    return get_color_value('primary_color', '#1C418C');
}
function get_secondary_color()
{
    return get_color_value('secondary_color', '#68BA62');
}
function get_accent_color()
{
    return get_color_value('accent_color', '#BD921E');
}
function get_text_color()
{
    return get_color_value('text_color', '#333333');
}
function get_text_light_color()
{
    return get_color_value('text_light_color', '#707070');
}
function get_background_color()
{
    return get_color_value('background_color', '#FFFFFF');
}
function get_background_light_color()
{
    return get_color_value('background_light_color', '#F4F4F4');
}
function get_border_color()
{
    return get_color_value('border_color', '#D1D1D1');
}
function get_link_color()
{
    return get_color_value('link_color', '#18BCA9');
}
function get_link_hover_color()
{
    return get_color_value('link_hover_color', '#008A81');
}
function get_button_bg_color()
{
    return get_color_value('button_bg_color', '#F49321');
}
function get_button_text_color()
{
    return get_color_value('button_text_color', '#FFFFFF');
}
function get_button_hover_color()
{
    return get_color_value('button_hover_color', '#d67d1a');
}
function get_header_bg_color()
{
    return get_color_value('header_bg_color', '#FFFFFF');
}
function get_header_text_color()
{
    return get_color_value('header_text_color', '#333333');
}
function get_footer_bg_color()
{
    return get_color_value('footer_bg_color', '#3A3A37');
}
function get_footer_text_color()
{
    return get_color_value('footer_text_color', '#FFFFFF');
}
function get_svg_color_1()
{
    return get_color_value('svg_color_1', '#525F66');
}
function get_svg_color_2()
{
    return get_color_value('svg_color_2', '#8FA7B3');
}
function get_error_color()
{
    return get_color_value('error_color', '#DB2323');
}
function get_warning_color()
{
    return get_color_value('warning_color', '#FFD500');
}
function get_success_color()
{
    return get_color_value('success_color', '#68BA62');
}
function get_info_color()
{
    return get_color_value('info_color', '#18BCA9');
}
function get_overlay_color()
{
    return get_color_value('overlay_color', '#000000');
}
function get_shadow_color()
{
    return get_color_value('shadow_color', '#000000');
}
function get_services_heading_color()
{
    return get_color_value('services_heading_color', '#F49321');
}
function get_footer_link_color()
{
    return get_color_value('footer_link_color', '#FFFFFF');
}
function get_footer_heading_color()
{
    return get_color_value('footer_heading_color', '#FFFFFF');
}

// Helper function to extract YouTube video ID from URL
function extract_youtube_id($url)
{
    if (empty($url))
        return '';

    // Patterns for different YouTube URL formats
    $patterns = [
        '/youtube\.com\/watch\?v=([a-zA-Z0-9_-]+)/',
        '/youtu\.be\/([a-zA-Z0-9_-]+)/',
        '/youtube\.com\/embed\/([a-zA-Z0-9_-]+)/',
        '/youtube\.com\/v\/([a-zA-Z0-9_-]+)/',
    ];

    foreach ($patterns as $pattern) {
        if (preg_match($pattern, $url, $matches)) {
            return $matches[1];
        }
    }

    // If no pattern matches, assume it's already a video ID
    return $url;
}

// Helper function to get YouTube home page video URL
function get_youtube_home_video()
{
    static $url = null;
    if ($url === null) {
        $conn = get_db_connection();
        if ($conn && !$conn->connect_error) {
            $result = $conn->query("SELECT setting_value FROM website_settings WHERE setting_key = 'youtube_home_video' LIMIT 1");
            if ($result && $row = $result->fetch_assoc()) {
                $url = trim($row['setting_value']);
            } else {
                $url = 'https://youtu.be/HuLcVb-Z3Bs'; // Default fallback - need to find actual home video
            }
        } else {
            $url = 'https://youtu.be/HuLcVb-Z3Bs'; // Default fallback
        }
    }
    return $url;
}

// Helper function to get YouTube background fire video URL (for all pages except home)
function get_youtube_background_video()
{
    static $url = null;
    if ($url === null) {
        $conn = get_db_connection();
        if ($conn && !$conn->connect_error) {
            $result = $conn->query("SELECT setting_value FROM website_settings WHERE setting_key = 'youtube_background_video' LIMIT 1");
            if ($result && $row = $result->fetch_assoc()) {
                $url = trim($row['setting_value']);
            } else {
                $url = 'https://www.youtube.com/watch?v=73R_z_eK6dM'; // Default fallback
            }
        } else {
            $url = 'https://www.youtube.com/watch?v=73R_z_eK6dM'; // Default fallback
        }
    }
    return $url;
}

// Helper function to get YouTube testimonial video 1 URL
function get_youtube_testimonial_1()
{
    static $url = null;
    if ($url === null) {
        $conn = get_db_connection();
        if ($conn && !$conn->connect_error) {
            $result = $conn->query("SELECT setting_value FROM website_settings WHERE setting_key = 'youtube_testimonial_1' LIMIT 1");
            if ($result && $row = $result->fetch_assoc()) {
                $url = trim($row['setting_value']);
            } else {
                $url = 'https://youtu.be/41FwAvgUJ7U'; // Default fallback
            }
        } else {
            $url = 'https://youtu.be/41FwAvgUJ7U'; // Default fallback
        }
    }
    return $url;
}

// Helper function to get YouTube testimonial video 2 URL
function get_youtube_testimonial_2()
{
    static $url = null;
    if ($url === null) {
        $conn = get_db_connection();
        if ($conn && !$conn->connect_error) {
            $result = $conn->query("SELECT setting_value FROM website_settings WHERE setting_key = 'youtube_testimonial_2' LIMIT 1");
            if ($result && $row = $result->fetch_assoc()) {
                $url = trim($row['setting_value']);
            } else {
                $url = 'https://youtu.be/gIGjb_WY_Wk'; // Default fallback
            }
        } else {
            $url = 'https://youtu.be/gIGjb_WY_Wk'; // Default fallback
        }
    }
    return $url;
}

// Legacy function names for backward compatibility
function get_youtube_video_1()
{
    return get_youtube_testimonial_1();
}

function get_youtube_video_2()
{
    return get_youtube_testimonial_2();
}

// Helper function to get all FAQs from database
function get_faqs()
{
    static $faqs = null;
    if ($faqs === null) {
        $conn = get_db_connection();
        if ($conn && !$conn->connect_error) {
            // Create table if it doesn't exist
            $conn->query("CREATE TABLE IF NOT EXISTS `faqs` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `question` text NOT NULL,
              `answer` text NOT NULL,
              `display_order` int(11) DEFAULT 0,
              `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
              `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
              PRIMARY KEY (`id`),
              KEY `display_order` (`display_order`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

            $result = $conn->query("SELECT * FROM faqs ORDER BY display_order ASC, id ASC");
            $faqs = [];
            if ($result) {
                while ($row = $result->fetch_assoc()) {
                    $faqs[] = $row;
                }
            }
        } else {
            $faqs = [];
        }
    }
    return $faqs;
}

// Helper function to get all services from database
function get_services($category_id = null)
{
    static $services_cache = [];
    $cache_key = $category_id ?? 'all';

    if (!isset($services_cache[$cache_key])) {
        $conn = get_db_connection();
        if ($conn && !$conn->connect_error) {
            if ($category_id) {
                $stmt = $conn->prepare("SELECT s.*, c.name as category_name 
                    FROM services s 
                    LEFT JOIN service_categories c ON s.category_id = c.id 
                    WHERE s.category_id = ?
                    ORDER BY s.display_order ASC, s.id ASC");
                $stmt->bind_param("i", $category_id);
                $stmt->execute();
                $result = $stmt->get_result();
            } else {
                $result = $conn->query("SELECT s.*, c.name as category_name 
                    FROM services s 
                    LEFT JOIN service_categories c ON s.category_id = c.id 
                    ORDER BY s.display_order ASC, s.id ASC");
            }

            $services = [];
            if ($result) {
                while ($row = $result->fetch_assoc()) {
                    $services[] = $row;
                }
            }

            if ($category_id) {
                $stmt->close();
            }

            $services_cache[$cache_key] = $services;
        } else {
            $services_cache[$cache_key] = [];
        }
    }

    return $services_cache[$cache_key];
}

// Helper function to get a single service by slug
function get_service_by_slug($slug)
{
    static $service_cache = [];

    if (!isset($service_cache[$slug])) {
        $conn = get_db_connection();
        if ($conn && !$conn->connect_error) {
            $stmt = $conn->prepare("SELECT s.*, c.name as category_name 
                FROM services s 
                LEFT JOIN service_categories c ON s.category_id = c.id 
                WHERE s.slug = ? OR s.url = ? 
                LIMIT 1");
            $stmt->bind_param("ss", $slug, $slug);
            $stmt->execute();
            $result = $stmt->get_result();
            $service = $result->fetch_assoc();
            $stmt->close();

            $service_cache[$slug] = $service ?: null;
        } else {
            $service_cache[$slug] = null;
        }
    }

    return $service_cache[$slug];
}

// Helper function to convert YouTube URL to embed format
function get_youtube_embed_url($youtube_url)
{
    $video_id = extract_youtube_id($youtube_url);
    if (empty($video_id))
        return '';
    return 'https://www.youtube.com/embed/' . $video_id;
}

// Helper function to convert YouTube URL to watch format
function get_youtube_watch_url($youtube_url)
{
    $video_id = extract_youtube_id($youtube_url);
    if (empty($video_id))
        return '';
    return 'https://www.youtube.com/watch?v=' . $video_id;
}

// Helper function to convert YouTube URL to short format (youtu.be)
function get_youtube_short_url($youtube_url)
{
    $video_id = extract_youtube_id($youtube_url);
    if (empty($video_id))
        return '';
    return 'https://youtu.be/' . $video_id;
}

// Helper function to get logo from database
function get_logo()
{
    static $logo = null;
    if ($logo === null) {
        $conn = get_db_connection();
        if ($conn && !$conn->connect_error) {
            $result = $conn->query("SELECT setting_value FROM website_settings WHERE setting_key = 'logo' LIMIT 1");
            if ($result && $row = $result->fetch_assoc()) {
                $logo = trim($row['setting_value']);
            } else {
                $logo = ''; // No default, return empty if not found
            }
        } else {
            $logo = '';
        }
    }
    return $logo;
}

// Helper function to get favicon from database
function get_favicon()
{
    static $favicon = null;
    if ($favicon === null) {
        $conn = get_db_connection();
        if ($conn && !$conn->connect_error) {
            $result = $conn->query("SELECT setting_value FROM website_settings WHERE setting_key = 'favicon' LIMIT 1");
            if ($result && $row = $result->fetch_assoc()) {
                $favicon = trim($row['setting_value']);
            } else {
                $favicon = ''; // No default, return empty if not found
            }
        } else {
            $favicon = '';
        }
    }
    return $favicon;
}

// Helper function to get website name from database
function get_website_name()
{
    static $name = null;
    if ($name === null) {
        $conn = get_db_connection();
        if ($conn && !$conn->connect_error) {
            $result = $conn->query("SELECT setting_value FROM website_settings WHERE setting_key = 'website_name' LIMIT 1");
            if ($result && $row = $result->fetch_assoc()) {
                $name = trim($row['setting_value']);
            } else {
                $name = 'Crest Chimney'; // Default fallback
            }
        } else {
            $name = 'Crest Chimney'; // Default fallback
        }
    }
    return $name;
}

// Helper function to get popup title from database
function get_popup_title()
{
    static $title = null;
    if ($title === null) {
        $conn = get_db_connection();
        if ($conn && !$conn->connect_error) {
            $result = $conn->query("SELECT setting_value FROM website_settings WHERE setting_key = 'popup_title' LIMIT 1");
            error_log("Popup Title Query - Result: " . ($result ? "SUCCESS" : "FAILED"));
            if ($result) {
                error_log("Popup Title Query - Rows: " . $result->num_rows);
                if ($row = $result->fetch_assoc()) {
                    $title = trim($row['setting_value']);
                    error_log("Popup Title Query - Found value: " . substr($title, 0, 50));
                } else {
                    $title = '';
                    error_log("Popup Title Query - No rows found");
                }
            } else {
                $title = '';
                error_log("Popup Title Query - Error: " . $conn->error);
            }
        } else {
            $title = '';
            error_log("Popup Title Query - Connection error");
        }
    }
    return $title;
}

// Helper function to get popup content from database
function get_popup_content()
{
    static $content = null;
    if ($content === null) {
        $conn = get_db_connection();
        if ($conn && !$conn->connect_error) {
            $result = $conn->query("SELECT setting_value FROM website_settings WHERE setting_key = 'popup_content' LIMIT 1");
            error_log("Popup Content Query - Result: " . ($result ? "SUCCESS" : "FAILED"));
            if ($result) {
                error_log("Popup Content Query - Rows: " . $result->num_rows);
                if ($row = $result->fetch_assoc()) {
                    $content = trim($row['setting_value']);
                    error_log("Popup Content Query - Found value length: " . strlen($content));
                } else {
                    $content = '';
                    error_log("Popup Content Query - No rows found");
                }
            } else {
                $content = '';
                error_log("Popup Content Query - Error: " . $conn->error);
            }
        } else {
            $content = '';
            error_log("Popup Content Query - Connection error");
        }
    }
    return $content;
}

// Helper function to generate popup HTML
function get_popup_html()
{
    $popup_title = get_popup_title();
    $popup_content = get_popup_content();
    $phone_tel = get_phone_number_tel();

    // Debug logging
    error_log("Popup Debug - Title: " . ($popup_title ?: 'EMPTY'));
    error_log("Popup Debug - Content: " . ($popup_content ?: 'EMPTY'));
    error_log("Popup Debug - Phone: " . ($phone_tel ?: 'EMPTY'));

    if (empty($popup_title) && empty($popup_content)) {
        error_log("Popup Debug - Both title and content are empty, returning empty string");
        return ''; // Don't show popup if both are empty
    }

    $html = '<div class="dialog-widget dialog-lightbox-widget dialog-type-buttons dialog-type-lightbox elementor-popup-modal"
        id="elementor-popup-modal-1786" aria-modal="true" role="document" tabindex="0" style="">
        <div class="dialog-widget-content dialog-lightbox-widget-content animated"><a role="button" tabindex="0"
                aria-label="Close" href="#" class="dialog-close-button dialog-lightbox-close-button"><i
                    class="eicon-close"></i></a>
            <div class="dialog-header dialog-lightbox-header"></div>
            <div class="dialog-message dialog-lightbox-message">
                <div data-elementor-type="popup" data-elementor-id="1786"
                    class="elementor elementor-1786 elementor-location-popup"
                    data-elementor-settings="{&quot;entrance_animation&quot;:&quot;fadeInDown&quot;,&quot;exit_animation&quot;:&quot;fadeInUp&quot;,&quot;entrance_animation_duration&quot;:{&quot;unit&quot;:&quot;px&quot;,&quot;size&quot;:1,&quot;sizes&quot;:[]},&quot;a11y_navigation&quot;:&quot;yes&quot;,&quot;triggers&quot;:{&quot;page_load_delay&quot;:10,&quot;page_load&quot;:&quot;yes&quot;},&quot;timing&quot;:[]}"
                    data-elementor-post-type="elementor_library" style="display: block;">
                    <div class="elementor-element elementor-element-df8f02f e-flex e-con-boxed e-con e-parent"
                        data-id="df8f02f" data-element_type="container"
                        data-settings="{&quot;background_background&quot;:&quot;classic&quot;}">
                        <div class="e-con-inner">
                            <div class="elementor-element elementor-element-a52b313 e-flex e-con-boxed e-con e-child"
                                data-id="a52b313" data-element_type="container">
                                <div class="e-con-inner">
                                    <div class="elementor-element elementor-element-31fbe95 elementor-widget elementor-widget-heading"
                                        data-id="31fbe95" data-element_type="widget" data-widget_type="heading.default">
                                        <div class="elementor-widget-container">
                                            <h2 class="elementor-heading-title elementor-size-default">' . htmlspecialchars($popup_title) . '</h2>
                                        </div>
                                    </div>
                                    <div class="elementor-element elementor-element-e3b3ffc elementor-widget elementor-widget-text-editor"
                                        data-id="e3b3ffc" data-element_type="widget"
                                        data-widget_type="text-editor.default">
                                        <div class="elementor-widget-container">
                                            <p>' . nl2br(htmlspecialchars($popup_content)) . '</p>
                                        </div>
                                    </div>
                                    <div class="elementor-element elementor-element-c24f679 e-flex e-con-boxed e-con e-child"
                                        data-id="c24f679" data-element_type="container">
                                        <div class="e-con-inner">
                                            <div class="elementor-element elementor-element-569d08b elementor-align-justify elementor-widget__width-initial elementor-widget elementor-widget-button"
                                                data-id="569d08b" data-element_type="widget"
                                                data-widget_type="button.default">
                                                <div class="elementor-widget-container">
                                                    <div class="elementor-button-wrapper"> <a
                                                            class="elementor-button elementor-button-link elementor-size-sm"
                                                            href="tel:' . htmlspecialchars($phone_tel) . '"> <span
                                                                class="elementor-button-content-wrapper"> <span
                                                                    class="elementor-button-text">Click to Call</span>
                                                            </span> </a></div>
                                                </div>
                                            </div>
                                            <div class="elementor-element elementor-element-5eb03f4 elementor-align-justify elementor-widget__width-initial elementor-widget elementor-widget-button"
                                                data-id="5eb03f4" data-element_type="widget"
                                                data-widget_type="button.default">
                                                <div class="elementor-widget-container">
                                                    <div class="elementor-button-wrapper"> <a
                                                            class="elementor-button elementor-button-link elementor-size-sm"
                                                            href="/contact-us/"> <span
                                                                class="elementor-button-content-wrapper"> <span
                                                                    class="elementor-button-text">Book Online</span>
                                                            </span> </a></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="dialog-buttons-wrapper dialog-lightbox-buttons-wrapper"></div>
        </div>
    </div>
    <script>
    console.log("Popup Debug - Title:", ' . json_encode($popup_title) . ');
    console.log("Popup Debug - Content:", ' . json_encode($popup_content) . ');
    console.log("Popup Debug - Phone:", ' . json_encode($phone_tel) . ');
    console.log("Popup Debug - Popup element exists:", document.getElementById("elementor-popup-modal-1786") ? "YES" : "NO");
    </script>';

    error_log("Popup Debug - HTML generated, length: " . strlen($html));
    return $html;
}

// Helper function to convert hex to rgb for rgba()
function hex2rgb($hex)
{
    if (empty($hex))
        return array(0, 0, 0);
    $hex = str_replace("#", "", $hex);
    if (strlen($hex) == 3) {
        $r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
        $g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
        $b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
    } else {
        $r = hexdec(substr($hex, 0, 2));
        $g = hexdec(substr($hex, 2, 2));
        $b = hexdec(substr($hex, 4, 2));
    }
    return array($r, $g, $b);
}

// Helper function to get map settings
function get_map_settings()
{
    static $map_settings = null;
    if ($map_settings === null) {
        $conn = get_db_connection();
        $result = $conn->query("SELECT * FROM map_settings LIMIT 1");
        if ($result && $row = $result->fetch_assoc()) {
            $map_settings = $row;
        } else {
            // Defaults
            $map_settings = [
                'latitude' => 32.7766642,
                'longitude' => -96.7969879,
                'zoom' => 9,
                'address_query' => '32.7766642,-96.79698789999999'
            ];
        }
    }
    return $map_settings;
}