<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}
// Google redirect URI to authenticate - If the captured code param exists and is valid - Google Authorization To get Access Token
if ( isset($_GET['code']) && !empty( $_GET['code'] ) ) {
    if ( SFTCY_Wordform_Connect_Googlesheet::wordform_connect_configure_google_authentication( $_GET['code'] ) ) {
         $wordform_connect_page_url = admin_url( 'admin.php?page=wordform-connects&configure=googlesheet&status=success' );
    }
    else {
         $wordform_connect_page_url = admin_url( 'admin.php?page=wordform-connects&configure=googlesheet&status=fail' );
    }                
    wp_redirect( $wordform_connect_page_url );
    exit();    
}

// Get Google Credentials
$credentials = SFTCY_Wordform_Connect_Googlesheet::get_google_credentials();
$google_client_id = array_filter( $credentials ) && isset( $credentials['clientID'] ) && ! empty( $credentials['clientID'] )? $credentials['clientID'] : '';
$google_client_secret = array_filter( $credentials ) && isset( $credentials['clientSecret'] ) && ! empty( $credentials['clientSecret'] )? $credentials['clientSecret'] : '';
// echo '<pre>';
// print_r( $credentials );
// echo '</pre>';

include_once SFTCY_WORDFORM_PLUGIN_DIR . 'admin/views/pages-header-template.php';

// If configured applications re-authentication requires or expires for a certain period not using the app then 'configured_status' change to 'inactive'
// to stop showing application name into select Application name dropdown menu
// Check Application Name: Google Sheet
if ( SFTCY_Wordform_Connect_Googlesheet::is_google_authencation_required() ) {
    $application_slug = 'googlesheet';
    SFTCY_Wordform::wordform_check_n_change_configured_status_applications( $application_slug );
}

// Get Zapier Info
$zapier_info = SFTCY_Wordform_Connect_Zapier::get_zapier_webhook_url();		
$zapier_webhook_url = isset( $zapier_info['webhookPostUrl'] )? $zapier_info['webhookPostUrl'] : '';	

?>
<div class="wrap" style="margin: 1%;">
<h2><i class="fa-brands fa-connectdevelop fa-fade fa-2xl" style="color: #74C0FC;"></i> WordForm Connects</h2>

    <!-- Start WordForm Connect Form -->
     <table class="table-width-100">
        <tbody>
            <td class="wordform-connection-select-form-name-td">
                <h4>Select Form</h4>
                <div class="wordform-connection-select-form-name-warpper-div">
                    <select id="WordFormConnectSelectForm" name="wordform-connect-selected-form">       
                        <option value=""><?php esc_html_e( 'Select Form', 'wordform-pro' ); ?></option>                 
                        <?php
                        $all_created_forms   = SFTCY_Wordform::sc_wordform_get_all_created_forms_data();
                        if ( isset( $all_created_forms ) && array_filter( $all_created_forms ) ) {
                            foreach ( $all_created_forms as $data ) {
                                echo '<option value="' . esc_attr( $data['form_id'] ) . '">' . esc_html( $data['form_name'] ) . '</option>';
                            }
                        }
                        ?>
                    </select>
                </div>
            </td>
            <td class="wordform-connection-arrow-hints-icon-wrapper-td">
                <div class="wordform-connection-arrow-hints-icon">
                    <span class="wordform-connection-create-icon">
                        <svg xmlns="http://www.w3.org/2000/svg" height="64" width="64" viewBox="0 0 512 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path fill="#ff5733" d="M0 256a256 256 0 1 0 512 0A256 256 0 1 0 0 256zm395.3 11.3l-112 112c-4.6 4.6-11.5 5.9-17.4 3.5s-9.9-8.3-9.9-14.8l0-64-96 0c-17.7 0-32-14.3-32-32l0-32c0-17.7 14.3-32 32-32l96 0 0-64c0-6.5 3.9-12.3 9.9-14.8s12.9-1.1 17.4 3.5l112 112c6.2 6.2 6.2 16.4 0 22.6z"/></svg>                        
                        <br/><button class="button button-primary"><i class="fa-brands fa-connectdevelop"></i> Create Connection</button>
                    </span>
                </div>
            </td>
            <td class="wordform-connection-select-connection-name-td">
                <h4>Select Application Name</h4>                
                <select id="WordFormSelectConnectionName" name="wordform-select-connection-name">   
                    <option value=""><?php esc_html_e( 'Select Application', 'wordform-pro' ); ?></option>                                         
                    <?php                        
                    $all_configured_applications   = SFTCY_Wordform::wordform_get_all_configured_application_names();                    
                    if ( isset( $all_configured_applications ) && array_filter( $all_configured_applications ) ) {
                        foreach ( $all_configured_applications as $data ) {
                            echo '<option value="' . esc_attr( $data['id'] ) . '" data-application-slug = "' . $data['application_slug'] . '" >' . esc_html( $data['application_name'] ) . '</option>';
                        }
                    }
                    ?>
                </select>                
            </td>
        </tbody>
     </table>
    <!-- End WordForm Connect Form -->

    <!-- Horizontal Divider -->
     <div class="wordform-horizontal-diver-1"></div>

    <!-- Start Configure Third-party Applications Modal Contents-->
	<table class="table-width-100 wordform-connect-page-configure-applications-table">
		<tbody>
            <thead>
                <tr>
                    <th colspan="2" class="wordform-configure-applications-th"><i class="fa-solid fa-gears"></i> Configure Applications</th>
                </tr>
            </thead>
            <tr>
                <td>
                    <h2>Google Sheet</h2>                    
                    <div data-thirdparty-program-name="GoogleSheetAPI" class="third-party-connect-library">
                        <span><i class="fa-solid fa-link fa-xl apps-configure-reconfigure-label"></i> Configure / Reconfigure</span>
                        <svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="150" height="150" viewBox="0 0 48 48">
                            <linearGradient id="gBjrhQfVvaLo6qORHi0_9a_6yIWVyFTE0no_gr1" x1="24" x2="24" y1="-166.87" y2="-248.839" gradientTransform="matrix(1 0 0 -1 0 -154)" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#21ad64"></stop><stop offset="1" stop-color="#088242"></stop></linearGradient><path fill="url(#gBjrhQfVvaLo6qORHi0_9a_6yIWVyFTE0no_gr1)" d="M39,15v27c0,1.105-0.895,2-2,2H11c-1.105,0-2-0.895-2-2V6c0-1.105,0.895-2,2-2h17L39,15z"></path><path fill="#107c42" d="M28,4v10c0,0.552,0.448,1,1,1h10L28,4z"></path><path d="M16,33c-1.103,0-2-0.897-2-2V21c0-1.103,0.897-2,2-2h16c1.103,0,2,0.897,2,2v10c0,1.103-0.897,2-2,2	H16z M30,29v-1h-4v1H30z M22,29v-1h-4v1H22z M30,24v-1h-4v1H30z M22,24v-1h-4v1H22z" opacity=".05"></path><path d="M16,32.5c-0.827,0-1.5-0.673-1.5-1.5V21c0-0.827,0.673-1.5,1.5-1.5h16c0.827,0,1.5,0.673,1.5,1.5v10	c0,0.827-0.673,1.5-1.5,1.5H16z M30.5,29.5v-2h-5v2H30.5z M22.5,29.5v-2h-5v2H22.5z M30.5,24.5v-2h-5v2H30.5z M22.5,24.5v-2h-5v2	H22.5z" opacity=".07"></path><path fill="#fff" d="M32,20H16c-0.553,0-1,0.448-1,1v10c0,0.552,0.447,1,1,1h16c0.553,0,1-0.448,1-1V21	C33,20.448,32.553,20,32,20z M31,25h-6v-3h6V25z M23,22v3h-6v-3H23z M17,27h6v3h-6V27z M25,30v-3h6v3H25z"></path>
                        </svg>                                                                
                    </div>    
                    <?php if ( ! SFTCY_Wordform_Connect_Googlesheet::is_google_authencation_required() ) {                              
                              if ( SFTCY_Wordform_Connect_Googlesheet::is_googlesheet_configured_status_active() ) {                                                            
                                echo '<h5 class="text-success"><i class="fa-solid fa-circle-check"></i> Configured [Active] </h5>';
                                echo '<button class="button button-secondary wordform-activate-deactivate-sending-forms-data" data-activate-deactivate-application-slug="googlesheet" data-application-status-change-to="inactive"><i class="fa-solid fa-link-slash"></i> Deactivate</button>';
                              }
                              else {
                                echo '<h5 class="text-disabled"><i class="fa-solid fa-circle-check"></i> Configured [Inactive] </h5>';
                                echo '<button class="button button-secondary wordform-activate-deactivate-sending-forms-data" data-activate-deactivate-application-slug="googlesheet" data-application-status-change-to="active"><i class="fa-solid fa-link"></i> Activate</button>';
                              }
                    }?>                    
                </td>

                <td>
                    <h2>Zapier</h2>
                    <div data-thirdparty-program-name="ZapierAPI" class="third-party-connect-library">
                        <span><i class="fa-solid fa-link fa-xl apps-configure-reconfigure-label"></i> Configure / Reconfigure</span>
                        <img src="<?php echo plugins_url('/images/zapier-logo.png', __DIR__ );?>" alt="Zapier" />                        
                    </div>    
                    <?php if ( isset( $zapier_webhook_url ) && ! empty( $zapier_webhook_url )  ) {                           
                           if ( SFTCY_Wordform_Connect_Zapier::is_zapier_configured_status_active() ) {
                                echo '<h5 class="text-success"><i class="fa-solid fa-circle-check"></i> Configured [Active] </h5>';
                                echo '<button class="button button-secondary wordform-activate-deactivate-sending-forms-data" data-activate-deactivate-application-slug="zapier" data-application-status-change-to="inactive"><i class="fa-solid fa-link-slash"></i> Deactivate</button>';
                           }
                           else {
                                echo '<h5 class="text-disabled"><i class="fa-solid fa-circle-check"></i> Configured [Inactive] </h5>';
                                echo '<button class="button button-secondary wordform-activate-deactivate-sending-forms-data" data-activate-deactivate-application-slug="zapier" data-application-status-change-to="active"><i class="fa-solid fa-link"></i> Activate</button>';
                           }
                    }?>                    
                </td>

            </tr>
		</tbody>	
	</table>


    <!-- Start Google Sheet Configure Modal Form -->
    <div id="GoogleSheetAPIModal" title="Google Sheet Configure" class="google-sheep-api-modal" style="display: none;">

                <!-- Start Gooogle Credentials Create Help Instructions -->
                <?php
                    $host = $_SERVER['SERVER_NAME'] ?? $_SERVER['HTTP_HOST'];
                    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';                    
                    $full_domain_with_protocol = $protocol . '://' . $host;
                    $google_auth_redirect_url = SftcyWordformConnectBase::get_wordform_connect_oauth_redirect_url();
                ?>

                <h5>How to create Google Authentication Client ID & Secret</h5>
                <div id="google-oauth-help" class="accordion">

                <h3>1. Open Google Cloud Console</h3>
                <div>
                    <p>
                    Go to <a href="https://console.cloud.google.com/" target="_blank">Google Cloud Console</a> 
                    and <strong>sign in with your Google account</strong>.  
                    <br>At the top bar, <em>select Project if already created, if not then create a new Project</em> for your app.
                    </p>
                </div>

                <h3>2. Configure OAuth Consent Screen</h3>
                <div>
                    <p>
                      Navigate to 
                      <a href="https://console.cloud.google.com/apis/credentials/consent" target="_blank">APIs &gt; OAuth consent screen</a>. 
                      Click <em>Get started</em> to create a new project, or select an existing one.
                    </p>

                    <ul>
                      <li><code>Fill in <em>App name</em>( like Wordform), <em>Support email</em>, <em>Authorized domain</em>.(Your authorized domain: <?php echo $full_domain_with_protocol;?>).</code></li>
                      <li><code>When <a href="https://console.cloud.google.com/auth/audience" target="_blank">publishing status</a> is Testing, add your Gmail address under Test Users.</code></li>
                      <li><code>In Production, click <em>Publish app</em> and complete the verification details as Google requires.</code></li>
                      <li>Save and continue.</li>
                    </ul>
                </div>

                <!--<h3>3. Enable Required APIs</h3>
                <div>
                    <p>
                    From <strong>APIs &amp; Services → Library</strong>, enable any Google APIs your app will use 
                    (e.g. Google Drive, Gmail).
                    </p>
                </div>-->

                <h3>4. Create OAuth Client ID</h3>
                <div>
                    <p>
                    Go to 
                    <a href="https://console.cloud.google.com/apis/credentials" target="_blank">
                    APIs &gt; Credentials</a> → <em>Create Credentials</em> → <strong>OAuth Client ID</strong>.
                    </p>
                    <p>Choose <strong>Web Application</strong> as the type and provide:</p>
                    <ul>
                    <li>
                        <strong>Authorized JavaScript origin</strong>: 
                        <code>
                            <span><?php echo $full_domain_with_protocol;?></span>
                            <a href="Javascript::void()" onclick="copyText(this)"><span title="Copy" class="dashicons dashicons-admin-page text-warning"></span></a> 
                            (<small>Copy-Paste this as authorized domain info</small>)
                        </code>                        
                    </li>
                    <li><strong>Authorized Redirect URI</strong>: 
                        <code>
                            <span><?php echo $google_auth_redirect_url;?></span>
                            <a href="Javascript::void()" onclick="copyText(this)"><span title="Copy" class="dashicons dashicons-admin-page text-warning"></span></a>
                            (<small>Copy-Paste this as authorized redirect URI</small>)
                        </code>
                    </li>
                    </ul>
                    <p><strong>Important:</strong> Redirect URI must be an <em>exact match</em>. 
                    Even small differences (http vs https, trailing slash, port) will cause 
                    <em>Authorized Redirect URI</em> errors.</p>
                </div>

                <h3>5. Copy Client ID & Secret</h3>
                <div>
                    <p>
                    After creating, copy your <strong>Client ID</strong> and <strong>Client Secret</strong>.
                    </p>
                    <p>
                    Paste them into the fields below:
                    <br><strong>Google Authentication Client ID</strong> & 
                    <strong>Google Authentication Client Secret</strong>.
                    </p>
                    <p>
                    You can always return to the 
                    <a href="https://console.cloud.google.com/apis/credentials" target="_blank">Credentials page</a> 
                    to regenerate or view your keys.
                    </p>
                </div>

                <!--<h3>6. Example Redirect URIs</h3>
                <div>
                    <ul>
                    <li>Production: <code>https://your-site.com/oauth2/callback</code></li>
                    <li>Local dev: <code>http://localhost:3000/oauth2/callback</code></li>
                    <li>Desktop app (loopback): <code>http://127.0.0.1:PORT/</code></li>
                    </ul>
                </div>-->

                </div><!-- #google-oauth-help  -->
                <script type="text/javascript">
                jQuery(document).ready(function($) {
                $("#google-oauth-help, #zapier-webhook-create-help").accordion({
                    collapsible: true,
                    active: false,
                    heightStyle: "content"
                });
                });
                </script>
               <!-- End Google Credentials Create Help Instructions -->

        <div class="google-sheet-configure-input-elements-wrapper" style="display: flex; flex-direction:column;">
            <div class="wordform-google-sheet-credentials-feedback-msg"></div>
            <div>
                <label for="googleAuthClientId"><i class="fa-solid fa-id-badge"></i> Google Authentication Client ID <span class="dashicons dashicons-editor-help" title="Create OAuth 2.0 credentials in Google Cloud Console → Copy the Client ID and paste here."></span></label><br/>
                <input type="text" id="googleAuthClientId" name="google-auth-client-id" class="google-auth-client-id" placeholder="Google Client ID" value="<?php esc_html_e( $google_client_id);?>">                
            </div>

            <div>
                <label for="googleAuthClientSecret"><i class="fa-solid fa-key"></i> Google Authentication Client Secret <span class="dashicons dashicons-editor-help" title="Create OAuth 2.0 credentials in Google Cloud Console → Copy the Client Secret and paste here."></span></label><br/>
                <input type="text" id="googleAuthClientSecret" name="google-auth-client-secret" class="google-auth-client-secret" placeholder="Google Client Secret" value="<?php esc_html_e( $google_client_secret);?>" >                
            </div>        

            <div>
                <?php $redirect_uri_tooltip_title = 'Copy this exact redirect URI and add it under Authorized Redirect URIs in Google Cloud Console when creating the OAuth Client ID. Any mismatch will break authentication.';?>                                
                <label for="googleAuthRedirectUrl">
                    <i class="fa-solid fa-link"></i> Google Authentication Redirect URL <span class="dashicons dashicons-editor-help" title="<?php echo $redirect_uri_tooltip_title;?>"></span>
                    <span style="display: none;"><?php echo $google_auth_redirect_url;?></span><a href="Javascript::void()" onclick="copyText(this)"><span title="Copy" class="dashicons dashicons-admin-page text-warning"></span></a>(<small>Copy-Paste this as authorized redirect URI</small>)
                </label><br/>
                <input type="text" id="googleAuthRedirectUrl" name="google-auth-redirect-url" class="google-auth-redirect-url" value="<?php echo $google_auth_redirect_url;?>">
            </div>

            <div class="wordform-configure-google-credentials-save-and-authentication-btn-div-wrapper">
                <button class="button button-primary wordform-configure-google-credentials-save-authentication-btn"><i class="fa-solid fa-gear"></i> Configure / Reconfigure</button>
            </div>

        </div>
    </div>
    <!-- End Google Sheet Configure Modal Form -->
    

    <!-- Start Zapier Configure Modal Form -->
    <div id="ZapierAPIModal" title="Zapier Connection Configure" class="" style="display: none;">

        <!-- Start Zapier Post Webhook URL Creation Steps -->
         <h5>How to create Zapier Webhook URL</h5>
         <div id="zapier-webhook-create-help" class="accordion">
            
            <h3>Step 1 - Log into Zapier</h3>
            <div>
                <p>Log into your <a href="https://zapier.com/app/zaps" target="_blank" rel="noopener">Zapier account</a> and click <em>Create Zap</em>.</p>
            </div>
            
            <h3>Step 2 - Choose Trigger App</h3>
            <div>
                <p>For the Trigger, search for and select <em>Webhooks by Zapier</em>, then choose <em>Catch Hook</em>.</p>
                <p><a href="https://help.zapier.com/hc/en-us/articles/8496288690317-Trigger-Zaps-from-webhooks" target="_blank" rel="noopener">Learn more about Catch Hook</a></p>
            </div>
            
            <h3>Step 3 - Copy Webhook URL</h3>
            <div>
                <p>Click <em>Continue</em> — Zapier will display your unique POST URL under <em>Custom Webhook URL</em>. Click <em>Copy</em> and paste that URL below into <em>Zapier Webhook URL</em> input field, so it sends data via HTTP POST.</p>
            </div>

            <h3>Step 4 - Test the Webhook</h3>
            <div>
                <p>Submit test data through the custom form you are connecting, then go back to Zapier and click <em>Test Trigger</em> to verify that it was received correctly.</p>
            </div>    
            
            <h3>Step 5 - Finish & Activate</h3>
            <div>
               <p>Name your Zap, turn it <strong>On</strong>, and you're all set — your data will now flow into Zapier in real time!</p>
               <p><a href="https://help.zapier.com/hc/en-us/articles/8496083355661-How-to-get-started-with-Webhooks-by-Zapier" target="_blank" rel="noopener">Full Zapier Webhooks guide</a></p>
            </div>    

        </div>
        <!-- End Zapier Post Webhook URL Creation Steps -->

        <div class="zapier-connection-input-elements-wrapper" style="display: flex; flex-direction:column;">
            <div class="wordform-zapier-app-feedback-msg"></div>                
            <div>
                <!-- <label for="ZapierWebhookUrl">Zapier Webhook URL</label><br/> -->
                <label for="ZapierWebhookUrl" class="wordai-label-webhook">
                <span class="dashicons dashicons-rest-api" aria-hidden="true"></span>
                Zapier Webhook URL
                </label><br/>
                <input type="text" id="ZapierWebhookUrl" name="zapier-webhook-url" class="zapier-webhook-url" value="<?php echo $zapier_webhook_url;?>" placeholder="https://hooks.zapier.com/hooks/catch/00000000/xxxxxxx/">
            </div>

            <div class="wordform-connect-save-update-zapier-info-button-div-wrapper">
                <button class="button button-primary wordform-connect-save-update-zapier-info-button"><i class="fa-solid fa-gear"></i> Save / Update</button>
            </div>

        </div>
    </div>
    <!-- End Zapier Configure Modal Form -->

   <!-- End Configure Third-party Applications Modal Contents--> 


    <!-- Start WordForm & Third-party Connection Modal Wrapper Element - On click Create Connection Button -->
    <div id="WordFormConnectionModal" title="WordForm Connection" class="" style="display: none;"></div>
    <!-- Start WordForm & Third-party Connection Modal - On click Create Connection Button -->

    <!-- Start WordForm Configure Success- Fail Message Display Modal - Based on configured application show modal -->    
    <?php
        if ( isset( $_GET['configure'] ) && ! empty( $_GET['configure'] ) && isset( $_GET['status'] ) && ! empty( $_GET['status'] )  ) {
            $configure_app = $_GET['configure'];
            $configure_app_result = $_GET['status'];
            switch ( $configure_app ) {
                case 'googlesheet':
                    if ( $configure_app_result == 'success' ) {
                        $configure_app_result_msg = '<h4 class="text-success"><i class="fa-solid fa-circle-check"></i> GoogleSheet Configured Successfully.</h4>';

                    }
                    else if ( $configure_app_result == 'fail' ) {
                        $configure_app_result_msg = '<h4 class="text-error"><i class="fa-solid fa-circle-exclamation"></i> GoogleSheet failed to Configure, please try again.</h4>';
                    }
                    break;
            } // switch
            echo '<div id="WordFormConnectionConfigureModal" class="WordFormConnectionConfigureModal" title="WordForm Configure">' . $configure_app_result_msg . '</div>';
        }
    ?>                            
    <!-- Start WordForm Configure Success- Fail Message Display Modal - Based on configured application show modal -->

    <!-- Start Application Activate or Deactivate Confirm Modal window Wrapper-->
     <div id="WordFormApplicationActivateDeactivateConfirmModal" class="WordFormApplicationActivateDeactivateConfirmModal" title="Confirm"></div>';
    <!-- End Application Activate or Deactivate Confirm Modal window Wrapper-->


</div><!-- /.wrap -->
