<div class="wrap">
    <?php
    if (get_option('io_reviews_widget_type') === false)
    {
        add_option('io_reviews_widget_type', 'io_testimonials');
    }

    $widget_type = get_option('io_reviews_widget_type');
    ?>
    <style>
		#wpcontent
		{
			background-color: #f0f0f1;
		}
		.nav-tabs .nav-link.active
		{
			background-color: #f0f0f1 !important;
		}
        .wrap .notice
        {
            display: none;
        }
		.wrap h2
		{
        	display: block;
        	height: 29.8906px;
        	margin: 0;
        	padding: 9px 0 4px 0;
            width: 100%;
        	font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
        	font-size: 23px;
        	font-weight: 400;
        	line-height: 29.9px;
        	color: rgb(29, 35, 39);
        	-webkit-font-smoothing: subpixel-antialiased;
        	unicode-bidi: isolate;
        	text-align: left;
        	box-sizing: border-box;
    	}
		.wrap h3
		{
        	display: block;
        	height: 18.1875px;
        	margin: 16.9px 0;
        	width: 100%;
        	font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
        	font-size: 16.9px;
        	font-weight: 600;
        	line-height: 18.2px;
        	color: rgb(29, 35, 39);
        	-webkit-font-smoothing: subpixel-antialiased;
        	unicode-bidi: isolate;
    	}
        #main-heading
        {
            text-align: left;
        }
        .gear-icon
        {
            position: absolute;
            top: 1.25rem;
            right: 1.25rem;
            font-size: 1.5rem;
        }
        .gear-icon i
        {
            font-size: 1.5rem;
            width: 1.5rem;
            height: 1.5rem;
            line-height: 1.5rem;
            display: inline-block;
            cursor: pointer;
        }
        .dropdown-menu
        {
            font-size: 1rem;
        }
        .btn
        {
            padding: 0.5rem 1rem;
        }
        .review-import-notice
        {
            font-size: 0.8em;
            color: #555;
            white-space: nowrap;
            display: flex;
            align-items: center;
            margin-left: .8rem;
            padding-bottom: 0.20rem;
        }
        .disabled-option {
            color: grey;
            cursor: not-allowed;
        }
    </style>

    <!-- Gear Icon for Menu -->
    <div class="gear-icon dropdown">
        <i class="fas fa-cog" id="debugMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></i>
        <div class="dropdown-menu dropdown-menu-right" aria-labelledby="debugMenu">
            <form method="POST" action="" class="px-4 py-3">
                <button type="submit" name="clear_imported_reviews" class="dropdown-item btn btn-danger">Clear Imported Google Reviews</button>
                <input type="hidden" name="active_tab" id="active_tab_delete" value="<?php echo $googleTabActive ? 'google-reviews' : 'iotestimonials'; ?>">
            </form>
        </div>
    </div>

    <h2 id="main-heading">InflatableOffice Review Management Interface</h2>

    <hr id="main-separator" class="my-4">

    <!-- Radio Buttons for Selecting Review Type -->
    <form method="POST" action="" id="review-type-form" style="margin-bottom: 1.25rem;">
        <label for="review_type" >
            <h3>Currently displaying:</h3>
        </label><br>

        <!-- IO Testimonials Option -->
        <input type="radio" id="io_testimonials" name="review_type" value="io_testimonials" <?php echo ($widget_type == 'io_testimonials') ? 'checked' : ''; ?>>
        <label for="io_testimonials">IO Testimonials</label><br>

        <!-- Google Reviews and Both Options (conditional) -->
        <?php
        $myplaceID = get_option('io_reviews_myplaceID');
        $io_gmb_access = get_option('io_gmb_access');
        $io_reviews_google = get_option('io_reviews_google');

        if (($myplaceID || $io_gmb_access) && $io_reviews_google):
            ?>
            <!-- Display options if myplaceID exists -->
            <input type="radio" id="google_reviews" name="review_type" value="google_reviews" <?php echo ($widget_type == 'google_reviews') ? 'checked' : ''; ?>>
            <label for="google_reviews">Google Reviews</label><br>
            <input type="radio" id="both_reviews" name="review_type" value="both_reviews" <?php echo ($widget_type == 'both_reviews') ? 'checked' : ''; ?>>
            <label for="both_reviews">Both</label><br>
            <button type="submit" class="button-primary">Save Selection</button>
        <?php else: ?>
            <!-- Display greyed-out options if no myplaceID -->
            <input type="radio" id="google_reviews" name="review_type" value="google_reviews" disabled>
            <label for="google_reviews" class="disabled-option">Google Reviews</label><br>
            <input type="radio" id="both_reviews" name="review_type" value="both_reviews" disabled>
            <label for="both_reviews" class="disabled-option">Both</label><br>
        <?php endif; ?>
    </form>

    <?php
    if (!get_option('io_reviews_myplaceID') || (get_option('io_gmb_access') && get_option('io_reviews_google'))):
        ?>
        <div class="nav-item review-import-notice">
            **In order to start importing your Google reviews, click the tab below ↓
        </div>
    <?php
    endif;
    ?>

    <br>

    <!-- Filters -->
    <div style="float: right;">
        <form method="POST" action="" class="form-inline mb-4">
            <label for="filter_rating" class="mr-2">Filter by Rating:</label>
            <select name="filter_rating" id="filter_rating" class="form-control">
                <option value="0" <?php echo isset($ratingFilter) && $ratingFilter == 0 ? 'selected' : ''; ?>>All Ratings</option>
                <option value="2" <?php echo isset($ratingFilter) && $ratingFilter == 2 ? 'selected' : ''; ?>>2 Stars & Up</option>
                <option value="3" <?php echo isset($ratingFilter) && $ratingFilter == 3 ? 'selected' : ''; ?>>3 Stars & Up</option>
                <option value="4" <?php echo isset($ratingFilter) && $ratingFilter == 4 ? 'selected' : ''; ?>>4 Stars & Up</option>
                <option value="5" <?php echo isset($ratingFilter) && $ratingFilter == 5 ? 'selected' : ''; ?>>5 Stars Only</option>
            </select>
            <label for="filter_time" class="ml-3 mr-2">Filter by Time:</label>
            <select name="filter_time" id="filter_time" class="form-control">
                <option value="all" <?php echo isset($timeFilter) && $timeFilter == 'all' ? 'selected' : ''; ?>>All Time</option>
                <option value="6_months" <?php echo isset($timeFilter) && $timeFilter == '6_months' ? 'selected' : ''; ?>>Last 6 Months</option>
                <option value="1_year" <?php echo isset($timeFilter) && $timeFilter == '1_year' ? 'selected' : ''; ?>>Last Year</option>
                <option value="3_years" <?php echo isset($timeFilter) && $timeFilter == '3_years' ? 'selected' : ''; ?>>Last 3 Years</option>
            </select>
            <input type="hidden" name="active_tab" id="active_tab_filter" value="<?php echo isset($googleTabActive) && $googleTabActive ? 'google-reviews' : 'iotestimonials'; ?>">
            <button type="submit" class="button-primary ml-2">Apply Filter</button>
        </form>
    </div>

    <div id="reviews-tables">
        <ul class="nav nav-tabs" id="reviewsTab" role="tablist">
            <li class="nav-item" role="presentation">
                <a class="nav-link <?php echo !isset($googleTabActive) || !$googleTabActive ? 'active' : ''; ?>" id="iotestimonials-tab" data-toggle="tab" href="#iotestimonials" role="tab" aria-controls="iotestimonials" aria-selected="<?php echo !isset($googleTabActive) || !$googleTabActive ? 'true' : 'false'; ?>">InflatableOffice Testimonials</a>
            </li>
            <li class="nav-item" role="presentation">
                <a class="nav-link <?php echo isset($googleTabActive) && $googleTabActive ? 'active' : ''; ?>" id="google-reviews-tab" data-toggle="tab" href="#google-reviews" role="tab" aria-controls="google-reviews" aria-selected="<?php echo isset($googleTabActive) && $googleTabActive ? 'true' : 'false'; ?>">Google Reviews</a>
            </li>
        </ul>
        <div class="tab-content" id="reviewsTabContent">
            <!-- IO Testimonials Tab -->
            <div class="tab-pane fade <?php echo !isset($googleTabActive) || !$googleTabActive ? 'show active' : ''; ?>" id="iotestimonials" role="tabpanel" aria-labelledby="iotestimonials-tab">
                <table class="table table-striped" id="iotestimonials-table" style="border: .0625rem solid #dee2e6; margin: 1.25rem 0;">
                    <thead>
                        <tr>
                            <th>Author</th>
                            <th>Rating</th>
                            <th>Review</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($reviewsIotestimonialsData)): ?>
                        <?php foreach ($reviewsIotestimonialsData as $review): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($review['testimonial_name']); ?></td>
                                <td><?php echo htmlspecialchars($review['testimonial_rating']); ?></td>
                                <td><?php echo htmlspecialchars($review['testimonial_description']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="3">No IO testimonials found.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Google Reviews Tab -->
            <div class="tab-pane fade <?php echo isset($googleTabActive) && $googleTabActive ? 'show active' : ''; ?>" id="google-reviews" role="tabpanel" aria-labelledby="google-reviews-tab">
                <?php
                $io_reviews_google = get_option('io_reviews_google');
                $candidates = isset($this->candidates) ? $this->candidates : null;
                if (!$myplaceID && !$io_reviews_google && empty($candidates)): ?>
                    <div id="content">
                        <form method="POST" action="" id="review-form">
                            <div class="form-group mb-2">
                                <br>
								<h3>
                                    <label for="business_name" style="margin-right: 0.625rem;">Enter your Google business name to retrieve your reviews: </label>
                                </h3>
                                <input type="text" class="ml-2" id="business_name" name="business_name" placeholder="Google Business Name" required>
                                <button type="submit" class="button-primary" style="margin-left: .625rem;">Search</button>
                            </div>
                            <input type="hidden" name="active_tab" value="google-reviews">
                        </form>
                    </div>
                <?php endif; ?>

                <?php if (!empty($candidates)): ?>
                    <?php require_once(__DIR__ . '/businessSelectionFormView.php'); ?>
                <?php endif; ?>

                <?php if (!empty($reviewsGoogleData)): ?>
                    <table class="table table-striped" id="google-reviews-table" style="border: .0625rem solid #dee2e6; margin: 1.25rem 0;">
                        <thead>
                            <tr>
                                <th>Author</th>
                                <th>Rating</th>
                                <th>Review</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($reviewsGoogleData as $review): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($review['author_name']); ?></td>
                                    <td><?php echo htmlspecialchars($review['rating']); ?></td>
                                    <td><?php echo htmlspecialchars($review['text']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div><!-- wrap -->

<div id="io-gmb-container" style="display:none;">
    <?php
// Load GMB credentials
    $json_credentials_path = plugin_dir_path(__FILE__) . '/../includes/GMB/GMB_Client_Credentials.json';
    $json_string = file_get_contents($json_credentials_path);
    $data = json_decode($json_string);

// Check for existing tokens
    $my_option = get_option('my_option_name');
    if (empty($my_option) && !isset($_GET['auth']))
    {
        $has_token = false;
    }
    else
    {
    // Load and initialize Google API client
        require_once(__DIR__ . '/../vendor/autoload.php');
        $client = new Google_Client();
        $client->setAuthConfig($json_credentials_path);
        $client->setScopes('https://www.googleapis.com/auth/business.manage');
        $client->setAccessType('offline');

    // Swap auth code for tokens
        $auth_code = $_GET['auth'];
        $access_token_data[] = $client->fetchAccessTokenWithAuthCode($auth_code);
        if (is_array($access_token_data))
        {
            $access_token_data = $access_token_data[0];
        }
        $access_token_data["state"] = 'authentication';

    // Save tokens to wp_options
        $string_to_save = json_encode($access_token_data);
        if (!add_option('io_gmb_access', $string_to_save))
        {
            update_option('io_gmb_access', $string_to_save);
            $has_token = true;
        }
        else
        {
            add_option('io_gmb_access', $string_to_save);
            $has_token = true;
        }
    }
    ?>

    <div class="sc_modal">
        <span class="sc_modal_close"></span>
        <div></div>
    </div>

    <div class="wrap">
        <h2>InflatableOffice Social Authentications</h2>
        <hr>
        <h3>Google My Business Posts Integration: </h3>
        <?php if ($has_token): ?>
            <img src="<?php echo plugins_url( '../images/checkmark_blue.png', __FILE__ ); ?>" alt="checkmark" width="35px"/>
            Authenticated
        <?php else: ?>
            <button class="button-primary" onclick="authorize()">
                Authorize
            </button>
        <?php endif; ?>
    </div>

    <script>
        function authorize()
        {
            let this_url = location.href;
            location.href = 'https://accounts.google.com/o/oauth2/auth?client_id=' + '<?php echo $data->web->client_id; ?>' + '&redirect_uri=' + '<?php echo $data->web->redirect_uris[0]; ?>' + '&scope=https://www.googleapis.com/auth/business.manage&response_type=code&access_type=offline' + '&state=' + this_url + '&prompt=consent';
        }
    </script>
</div>

<script>
    // Define secretCode outside the event listener so it persists across key presses
    let secretCode = '';

    document.addEventListener('keydown', function(e) {
        const keyCombination = e.shiftKey && e.code === 'KeyD';
        const expectedSequence = 'DAN!';

        if (keyCombination || secretCode.length > 0) {
            secretCode += e.key.toUpperCase();

            if (secretCode === expectedSequence) {
                const container = document.getElementById('io-gmb-container');
                container.style.display = 'block';
                console.log("Secret code matched! Toggling visibility.");
                secretCode = '';  // Reset code after successful toggle
            }
        }

        // Reset the sequence if a wrong key is pressed
        if (!e.shiftKey && e.key.toUpperCase() !== expectedSequence[secretCode.length - 1])
        {
            console.log("Wrong key pressed. Resetting secret code.");
            secretCode = '';
        }
    });
</script>