<?php

/**
 * SocialPromoter — Connected Platforms page.
 *
 * @package PublisherKits_SocialPromoter
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
$connectors = PKITS_SP_Platform_Registry::get_all();
$callback_url = PKITS_SP_Admin::callback_url();
$platform_icons = array(
    'x'        => 'X',
    'facebook' => 'f',
    'linkedin' => 'in',
    'bluesky'  => 'BS',
);
// Count connections for sidebar.
$total_platforms = count( $connectors );
$credential_based = array();
$relay_based = array();
$connected_count = 0;
foreach ( $connectors as $slug => $connector ) {
    if ( 'relay' === $connector->get_auth_type() ) {
        $relay_based[] = $connector->get_label();
    } else {
        $credential_based[] = $connector->get_label();
    }
    $accounts = PKITS_SP_Accounts::get_by_platform( $slug );
    if ( !empty( $accounts ) ) {
        $connected_count++;
    }
}
?>
<div class="wrap pkits-sp-wrap">

	<h1 class="pkits-sp-page-title">
		<span class="pkits-sp-logo-mark">SP</span>
		<?php 
esc_html_e( 'SocialPromoter &mdash; Connected Platforms', 'publisherkits-socialpromoter' );
?>
	</h1>
	<p class="pkits-sp-intro"><?php 
esc_html_e( 'Connect and manage your social accounts.', 'publisherkits-socialpromoter' );
?></p>

	<div class="pkits-sp-page-layout">

		<!-- ── MAIN COLUMN ──────────────────────────────────────── -->
		<div class="pkits-sp-page-main">

			<!-- Callback URL -->
			<div class="pkits-sp-callback-box">
				<div class="pkits-sp-card-title">
					<span style="font-size:16px;">&#128279;</span>
					<?php 
esc_html_e( 'Callback URL', 'publisherkits-socialpromoter' );
?>
				</div>
				<div class="pkits-sp-callback-url-row">
					<span style="flex:1;"><?php 
echo esc_html( $callback_url );
?></span>
					<button type="button" class="pkits-sp-copy-url-btn" data-url="<?php 
echo esc_attr( $callback_url );
?>">
						&#9107; <?php 
esc_html_e( 'Copy', 'publisherkits-socialpromoter' );
?>
					</button>
				</div>
				<p style="font-size:12px;color:#8a9ab0;margin:4px 0 0;">
					<?php 
esc_html_e( 'Add this URL to your developer app settings before connecting.', 'publisherkits-socialpromoter' );
?>
				</p>
			</div>

			<h2 style="font-family:'Roboto Slab',Georgia,serif;font-size:16px;font-weight:600;color:#1a2d4a;margin:0 0 12px;">
				<?php 
esc_html_e( 'Platform connections', 'publisherkits-socialpromoter' );
?>
			</h2>

			<?php 
foreach ( $connectors as $slug => $connector ) {
    $creds = PKITS_SP_Accounts::get_app_credentials( $slug );
    $accounts = PKITS_SP_Accounts::get_by_platform( $slug );
    $fields = $connector->get_credential_fields();
    $desc = $connector->get_accounts_description();
    $is_relay = 'relay' === $connector->get_auth_type();
    $is_apppw = 'apppassword' === $connector->get_auth_type();
    $icon_label = ( isset( $platform_icons[$slug] ) ? $platform_icons[$slug] : strtoupper( substr( $slug, 0, 2 ) ) );
    // Determine status. Escaped at output, not here.
    if ( !empty( $accounts ) ) {
        $status_class = 'pkits-sp-plat-status-connected';
        $status_text = __( 'Connected', 'publisherkits-socialpromoter' );
    } elseif ( $is_relay || $is_apppw || !empty( $creds ) ) {
        $status_class = 'pkits-sp-plat-status-ready';
        $status_text = __( 'Ready to connect', 'publisherkits-socialpromoter' );
    } else {
        $status_class = 'pkits-sp-plat-status-needs';
        $status_text = __( 'Needs credentials', 'publisherkits-socialpromoter' );
    }
    ?>
				<div class="pkits-sp-plat-card">
					<div class="pkits-sp-plat-card-header">
						<div class="pkits-sp-plat-icon pkits-sp-plat-icon-<?php 
    echo esc_attr( $slug );
    ?>">
							<?php 
    echo esc_html( $icon_label );
    ?>
						</div>
						<span class="pkits-sp-plat-name"><?php 
    echo esc_html( $connector->get_label() );
    ?></span>
						<span class="pkits-sp-plat-status <?php 
    echo esc_attr( $status_class );
    ?>">
							<?php 
    echo esc_html( $status_text );
    ?>
						</span>
					</div>
					<div class="pkits-sp-plat-card-body">

						<?php 
    if ( $desc ) {
        ?>
							<div class="pkits-sp-plat-notice">
								<?php 
        echo wp_kses( $desc, array(
            'a' => array(
                'href'   => array(),
                'target' => array(),
                'rel'    => array(),
            ),
        ) );
        ?>
							</div>
						<?php 
    }
    ?>

						<?php 
    if ( $is_apppw ) {
        ?>
							<form method="post" action="<?php 
        echo esc_url( admin_url( 'admin-post.php' ) );
        ?>">
								<?php 
        wp_nonce_field( 'pkits_sp_bluesky_connect' );
        ?>
								<input type="hidden" name="action" value="pkits_sp_bluesky_connect" />
								<div class="pkits-sp-form-grid single" style="margin-bottom:14px;">
									<div class="pkits-sp-form-group">
										<label for="bluesky_handle"><?php 
        esc_html_e( 'Handle', 'publisherkits-socialpromoter' );
        ?></label>
										<input type="text" id="bluesky_handle" name="bluesky_handle" value="" placeholder="yourname.bsky.social" autocomplete="off" />
									</div>
									<div class="pkits-sp-form-group">
										<label for="bluesky_app_password"><?php 
        esc_html_e( 'App password', 'publisherkits-socialpromoter' );
        ?></label>
										<input type="password" id="bluesky_app_password" name="bluesky_app_password" value="" placeholder="xxxx-xxxx-xxxx-xxxx" autocomplete="off" />
									</div>
								</div>
								<button type="submit" class="pkits-sp-btn-primary" style="font-size:13px;">
									<?php 
        printf( 
            /* translators: %s: platform label */
            esc_html__( 'Connect %s account', 'publisherkits-socialpromoter' ),
            esc_html( $connector->get_label() )
         );
        ?>
								</button>
							</form>
						<?php 
    } else {
        ?>
						<form method="post" action="<?php 
        echo esc_url( admin_url( 'admin-post.php' ) );
        ?>">
							<?php 
        wp_nonce_field( 'pkits_sp_save_credentials' );
        ?>
							<input type="hidden" name="action" value="pkits_sp_save_credentials" />
							<input type="hidden" name="pkits_sp_platform" value="<?php 
        echo esc_attr( $slug );
        ?>" />

							<?php 
        if ( !empty( $fields ) ) {
            ?>
								<div class="pkits-sp-form-grid single" style="margin-bottom:14px;">
									<?php 
            foreach ( $fields as $field ) {
                $field_id = sanitize_key( $field['id'] );
                $field_type = ( isset( $field['type'] ) ? $field['type'] : 'text' );
                $field_value = ( isset( $creds[$field_id] ) ? $creds[$field_id] : '' );
                ?>
										<?php 
                if ( 'checkbox' === $field_type ) {
                    ?>
										<div class="pkits-sp-form-group">
											<label class="pkits-sp-toggle-label" for="<?php 
                    echo esc_attr( $slug . '_' . $field_id );
                    ?>">
												<input type="checkbox" id="<?php 
                    echo esc_attr( $slug . '_' . $field_id );
                    ?>" name="<?php 
                    echo esc_attr( $field_id );
                    ?>" value="1" <?php 
                    checked( !empty( $field_value ) );
                    ?> />
												<?php 
                    echo esc_html( $field['label'] );
                    ?>
											</label>
											<?php 
                    if ( !empty( $field['help'] ) ) {
                        ?>
												<p class="pkits-sp-card-desc" style="margin:4px 0 0;font-size:11px;line-height:1.5;"><?php 
                        echo esc_html( $field['help'] );
                        ?></p>
											<?php 
                    }
                    ?>
										</div>
										<?php 
                } else {
                    ?>
										<div class="pkits-sp-form-group">
											<label for="<?php 
                    echo esc_attr( $slug . '_' . $field_id );
                    ?>">
												<?php 
                    echo esc_html( $field['label'] );
                    ?>
											</label>
											<input
												type="<?php 
                    echo esc_attr( $field_type );
                    ?>"
												id="<?php 
                    echo esc_attr( $slug . '_' . $field_id );
                    ?>"
												name="<?php 
                    echo esc_attr( $field_id );
                    ?>"
												value="<?php 
                    echo esc_attr( $field_value );
                    ?>"
												autocomplete="off"
											/>
										</div>
										<?php 
                }
                ?>
									<?php 
            }
            ?>
								</div>
							<?php 
        }
        ?>

							<button type="submit" class="pkits-sp-btn-primary" style="font-size:13px;">
								<?php 
        if ( $is_relay ) {
            printf( 
                /* translators: %s: platform label */
                esc_html__( 'Connect %s account', 'publisherkits-socialpromoter' ),
                esc_html( $connector->get_label() )
             );
        } else {
            printf( 
                /* translators: %s: platform label */
                esc_html__( 'Save &amp; connect %s', 'publisherkits-socialpromoter' ),
                esc_html( $connector->get_label() )
             );
        }
        ?>
							</button>
						</form>
						<?php 
    }
    ?>

						<?php 
    if ( !empty( $accounts ) ) {
        ?>
							<?php 
        $multi_account = count( $accounts ) > 1;
        $active_form = 'pkits-sp-active-' . esc_attr( $slug );
        ?>
							<?php 
        if ( $multi_account ) {
            ?>
								<form id="<?php 
            echo esc_attr( $active_form );
            ?>" method="post" action="<?php 
            echo esc_url( admin_url( 'admin-post.php' ) );
            ?>">
									<?php 
            wp_nonce_field( 'pkits_sp_save_active_accounts' );
            ?>
									<input type="hidden" name="action" value="pkits_sp_save_active_accounts" />
									<input type="hidden" name="pkits_sp_platform" value="<?php 
            echo esc_attr( $slug );
            ?>" />
								</form>
							<?php 
        }
        ?>
							<table class="pkits-sp-accounts-table widefat striped" style="margin-top:16px;">
								<thead>
									<tr>
										<?php 
        if ( $multi_account ) {
            ?>
											<th style="width:120px;"><?php 
            esc_html_e( 'Use for posting', 'publisherkits-socialpromoter' );
            ?></th>
										<?php 
        }
        ?>
										<th><?php 
        esc_html_e( 'Account', 'publisherkits-socialpromoter' );
        ?></th>
										<?php 
        if ( 'linkedin' === $slug ) {
            ?>
											<th><?php 
            esc_html_e( 'Type', 'publisherkits-socialpromoter' );
            ?></th>
										<?php 
        }
        ?>
										<th><?php 
        esc_html_e( 'Connected', 'publisherkits-socialpromoter' );
        ?></th>
										<th></th>
									</tr>
								</thead>
								<tbody>
									<?php 
        foreach ( $accounts as $storage_id => $account ) {
            ?>
										<tr>
											<?php 
            if ( $multi_account ) {
                ?>
												<td style="text-align:center;">
													<input type="checkbox"
														form="<?php 
                echo esc_attr( $active_form );
                ?>"
														name="pkits_sp_active_accounts[]"
														value="<?php 
                echo esc_attr( $storage_id );
                ?>"
														<?php 
                checked( PKITS_SP_Accounts::is_active( $account ) );
                ?> />
												</td>
											<?php 
            }
            ?>
											<td><strong><?php 
            echo esc_html( $account['label'] );
            ?></strong></td>
											<?php 
            if ( 'linkedin' === $slug ) {
                ?>
												<td><?php 
                echo esc_html( ucfirst( $account['account_type'] ?? '-' ) );
                ?></td>
											<?php 
            }
            ?>
											<td><?php 
            echo esc_html( $account['connected_at'] ?? '-' );
            ?></td>
											<td>
												<form method="post" action="<?php 
            echo esc_url( admin_url( 'admin-post.php' ) );
            ?>" style="display:inline;">
													<?php 
            wp_nonce_field( 'pkits_sp_delete_account' );
            ?>
													<input type="hidden" name="action" value="pkits_sp_delete_account" />
													<input type="hidden" name="pkits_sp_storage_id" value="<?php 
            echo esc_attr( $storage_id );
            ?>" />
													<button type="submit" class="button button-small"><?php 
            esc_html_e( 'Disconnect', 'publisherkits-socialpromoter' );
            ?></button>
												</form>
											</td>
										</tr>
									<?php 
        }
        ?>
								</tbody>
							</table>
							<?php 
        if ( $multi_account ) {
            ?>
								<div style="margin-top:12px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
									<button type="submit" form="<?php 
            echo esc_attr( $active_form );
            ?>" class="pkits-sp-btn-primary" style="font-size:13px;">
										<?php 
            esc_html_e( 'Save posting selection', 'publisherkits-socialpromoter' );
            ?>
									</button>
									<span style="font-size:12px;color:#8a9ab0;">
										<?php 
            esc_html_e( 'Unticked accounts stay connected but are hidden from Compose and the post nudge.', 'publisherkits-socialpromoter' );
            ?>
									</span>
								</div>
							<?php 
        }
        ?>
						<?php 
    }
    ?>

					</div>
				</div>
			<?php 
}
?>

		</div>

		<!-- ── SIDEBAR ───────────────────────────────────────────── -->
		<div class="pkits-sp-page-aside">

			<!-- Connections overview -->
			<div class="pkits-sp-widget">
				<div class="pkits-sp-widget-header">
					<div class="pkits-sp-widget-icon">&#9783;</div>
					<h3 class="pkits-sp-widget-title"><?php 
esc_html_e( 'Connections overview', 'publisherkits-socialpromoter' );
?></h3>
				</div>
				<div class="pkits-sp-widget-body">
					<div class="pkits-sp-summary-row">
						<div class="pkits-sp-summary-label"><?php 
esc_html_e( 'Platforms available', 'publisherkits-socialpromoter' );
?></div>
						<div class="pkits-sp-summary-value"><?php 
echo (int) $total_platforms;
?></div>
					</div>
					<?php 
if ( $credential_based ) {
    ?>
					<div class="pkits-sp-summary-row">
						<div class="pkits-sp-summary-label"><?php 
    esc_html_e( 'Credential-based', 'publisherkits-socialpromoter' );
    ?></div>
						<div class="pkits-sp-summary-value"><?php 
    echo esc_html( implode( ', ', $credential_based ) );
    ?></div>
					</div>
					<?php 
}
?>
					<?php 
if ( $relay_based ) {
    ?>
					<div class="pkits-sp-summary-row">
						<div class="pkits-sp-summary-label"><?php 
    esc_html_e( 'Shared app', 'publisherkits-socialpromoter' );
    ?></div>
						<div class="pkits-sp-summary-value"><?php 
    echo esc_html( implode( ', ', $relay_based ) );
    ?></div>
					</div>
					<?php 
}
?>
					<div class="pkits-sp-summary-row">
						<div class="pkits-sp-summary-label"><?php 
esc_html_e( 'Callback URL', 'publisherkits-socialpromoter' );
?></div>
						<div class="pkits-sp-summary-value"><?php 
esc_html_e( '1 shared URL', 'publisherkits-socialpromoter' );
?></div>
					</div>
				</div>
			</div>

			<!-- Helpful guidance -->
			<div class="pkits-sp-widget pkits-sp-guidance-widget">
				<div class="pkits-sp-widget-header">
					<div class="pkits-sp-widget-icon">&#128161;</div>
					<h3 class="pkits-sp-widget-title"><?php 
esc_html_e( 'Helpful guidance', 'publisherkits-socialpromoter' );
?></h3>
				</div>
				<div class="pkits-sp-widget-body">
					<ul class="pkits-sp-guidance-list">
						<li><?php 
esc_html_e( 'Add the callback URL to your developer app settings before connecting.', 'publisherkits-socialpromoter' );
?></li>
						<li><?php 
esc_html_e( 'Keep your app credentials secure and never share them.', 'publisherkits-socialpromoter' );
?></li>
						<li><?php 
esc_html_e( 'Test each connection after setup to ensure posting works correctly.', 'publisherkits-socialpromoter' );
?></li>
						<li><?php 
esc_html_e( 'More platforms can be added later as needed.', 'publisherkits-socialpromoter' );
?></li>
					</ul>
				</div>
			</div>

			<!-- How it works -->
			<div class="pkits-sp-widget pkits-sp-guidance-widget">
				<div class="pkits-sp-widget-header">
					<div class="pkits-sp-widget-icon">&#128640;</div>
					<h3 class="pkits-sp-widget-title"><?php 
esc_html_e( 'How it works', 'publisherkits-socialpromoter' );
?></h3>
				</div>
				<div class="pkits-sp-widget-body">
					<p style="font-size:12px;color:#1a2d4a;line-height:1.6;margin:0 0 8px;">
						<?php 
esc_html_e( 'Connect your platforms first by adding credentials or authorising your account.', 'publisherkits-socialpromoter' );
?>
					</p>
					<p style="font-size:12px;color:#1a2d4a;line-height:1.6;margin:0 0 8px;">
						<?php 
esc_html_e( 'Then use Compose, or the SocialPromoter panel on any post, to send and schedule.', 'publisherkits-socialpromoter' );
?>
					</p>
					<?php 
?>
				</div>
			</div>

		</div>
	</div>

</div>

<?php 
ob_start();
?>
document.addEventListener( 'DOMContentLoaded', function() {
	document.querySelectorAll( '.pkits-sp-copy-url-btn' ).forEach( function( btn ) {
		btn.addEventListener( 'click', function() {
			var url = this.dataset.url;
			if ( navigator.clipboard ) {
				navigator.clipboard.writeText( url ).then( function() {
					btn.textContent = '✓ Copied';
					setTimeout( function() { btn.innerHTML = '&#9107; Copy'; }, 2000 );
				} );
			}
		} );
	} );
} );
<?php 
wp_add_inline_script( 'pkits-sp-admin', ob_get_clean() );