<?php
/*
Template Name: SM Dashboard
*/

if ( ! defined( 'ABSPATH' ) ) {
	wp_die( esc_html__( 'You can\'t access this page', 'shop-manager' ) );
}

if ( ! defined( 'WPKIN_SM_URL' ) ) {
    define( 'WPKIN_SM_URL', plugin_dir_url( __FILE__ ) );
}
if ( ! defined( 'WPKIN_SM_PATH' ) ) {
    define( 'WPKIN_SM_PATH', plugin_dir_path( __FILE__ ) );
}

// Use get_query_var() for registered vars (safe from canonical redirect stripping).
// Fall back to $_GET so direct links still work before flush_rewrite_rules runs.
$sm_action   = sanitize_key( get_query_var( 'sm_action' ) ?: ( isset( $_GET['sm_action'] ) ? sanitize_key( wp_unslash( $_GET['sm_action'] ) ) : '' ) ); // phpcs:ignore WordPress.Security.NonceVerification
$reset_key   = sanitize_text_field( get_query_var( 'sm_key' ) ?: ( isset( $_GET['sm_key'] ) ? wp_unslash( $_GET['sm_key'] ) : '' ) ); // phpcs:ignore WordPress.Security.NonceVerification
$reset_login = sanitize_user( get_query_var( 'sm_login' ) ?: ( isset( $_GET['sm_login'] ) ? wp_unslash( $_GET['sm_login'] ) : '' ) ); // phpcs:ignore WordPress.Security.NonceVerification

$error_message   = '';
$success_message = '';
$pw_user         = null;

// ── Set New Password ─────────────────────────────────────────────────────────
if ( $sm_action === 'set-password' ) {
    if ( ! $reset_key || ! $reset_login ) {
        $sm_action     = 'invalid-key';
        $error_message = __( 'Invalid password setup link. Please request a new one.', 'shop-manager' );
    } else {
        $pw_user = check_password_reset_key( $reset_key, $reset_login );
        if ( is_wp_error( $pw_user ) ) {
            $sm_action     = 'invalid-key';
            $error_message = __( 'This link is invalid or has already been used. Please request a new one.', 'shop-manager' );
        } elseif (
            isset( $_POST['sm_set_password_nonce'] ) &&
            wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['sm_set_password_nonce'] ) ), 'sm_set_password_action' )
        ) {
            $pass1 = isset( $_POST['pass1'] ) ? wp_unslash( $_POST['pass1'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput
            $pass2 = isset( $_POST['pass2'] ) ? wp_unslash( $_POST['pass2'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput
            if ( empty( $pass1 ) ) {
                $error_message = __( 'Please enter a new password.', 'shop-manager' );
            } elseif ( $pass1 !== $pass2 ) {
                $error_message = __( 'Passwords do not match. Please try again.', 'shop-manager' );
            } elseif ( mb_strlen( $pass1 ) < 8 ) {
                $error_message = __( 'Password must be at least 8 characters long.', 'shop-manager' );
            } else {
                reset_password( $pw_user, $pass1 );
                wp_set_auth_cookie( $pw_user->ID );
                wp_safe_redirect( home_url( '/sm-dashboard/' ) );
                exit;
            }
        }
    }
}

// ── Forgot Password ──────────────────────────────────────────────────────────
if ( $sm_action === 'lost-password' ) {
    if (
        isset( $_POST['sm_lost_password_nonce'] ) &&
        wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['sm_lost_password_nonce'] ) ), 'sm_lost_password_action' )
    ) {
        $user_input = isset( $_POST['user_login'] ) ? sanitize_text_field( wp_unslash( $_POST['user_login'] ) ) : '';
        if ( empty( $user_input ) ) {
            $error_message = __( 'Please enter your username or email address.', 'shop-manager' );
        } else {
            $lost_user = is_email( $user_input )
                ? get_user_by( 'email', $user_input )
                : get_user_by( 'login', $user_input );
            if ( $lost_user ) {
                $key = get_password_reset_key( $lost_user );
                if ( ! is_wp_error( $key ) ) {
                    $reset_url = add_query_arg(
                        [
                            'sm_action' => 'set-password',
                            'sm_key'    => $key,
                            'sm_login'  => $lost_user->user_login,
                        ],
                        home_url( '/sm-dashboard/' )
                    );
                    $site_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
                    $subject   = sprintf( '[%s] %s', $site_name, __( 'Password Reset Request', 'shop-manager' ) );
                    $body      = sprintf( "Hi %s,\r\n\r\n", $lost_user->display_name ?: $lost_user->user_login );
                    $body     .= sprintf( "A password reset was requested for your account on %s.\r\n\r\n", $site_name );
                    $body     .= "Click the link below to set a new password:\r\n\r\n";
                    $body     .= $reset_url . "\r\n\r\n";
                    $body     .= "This link will expire in 24 hours.\r\n\r\n";
                    $body     .= "If you did not request this, please ignore this email.";
                    wp_mail( $lost_user->user_email, $subject, $body );
                }
            }
            $success_message = __( 'If an account with that username or email exists, a password reset link has been sent. Please check your inbox.', 'shop-manager' );
        }
    }
}

// ── Login form submission ────────────────────────────────────────────────────
if (
    ! $sm_action &&
    isset( $_POST['sm_login_nonce'] ) &&
    wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['sm_login_nonce'] ) ), 'sm_login_action' )
) {
    if ( isset( $_POST['log'], $_POST['pwd'] ) ) {
        $creds = [
            'user_login'    => sanitize_user( wp_unslash( $_POST['log'] ) ),
            'user_password' => sanitize_text_field( wp_unslash( $_POST['pwd'] ) ),
            'remember'      => isset( $_POST['rememberme'] ),
        ];
        $user = wp_signon( $creds, false );
        if ( is_wp_error( $user ) ) {
            $error_message = $user->get_error_message();
        } else {
            wp_safe_redirect( home_url( '/sm-dashboard' ) );
            exit;
        }
    }
}

$lost_password_url = home_url( '/sm-dashboard/?sm_action=lost-password' );

?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <?php wp_head(); ?>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
</head>
<body>
    <?php if ( is_page_template( 'templates/wpkin-sm-dashboard.php' ) ) : ?>

    <?php if ( $sm_action === 'set-password' && $pw_user instanceof \WP_User ) : ?>
        <!-- ── Set New Password Form ── -->
        <div class="wpkin-sm-login-form-wrapper">
            <div class="wpkin-sm-login-form">
                <h2><?php esc_html_e( 'Set Your Password', 'shop-manager' ); ?></h2>
                <?php if ( $error_message ) : ?>
                    <div class="error-message"><?php echo wp_kses_post( $error_message ); ?></div>
                <?php endif; ?>
                <form method="post" action="">
                    <?php wp_nonce_field( 'sm_set_password_action', 'sm_set_password_nonce' ); ?>
                    <input type="hidden" name="sm_action" value="set-password">
                    <p class="login-container">
                        <label for="pass1"><?php esc_html_e( 'New Password', 'shop-manager' ); ?></label>
                        <div class="pw-wrap">
                            <input type="password" name="pass1" id="pass1" class="login-input" autocomplete="new-password" minlength="8" required>
                            <button type="button" class="pw-toggle" data-target="pass1" aria-label="<?php esc_attr_e( 'Show password', 'shop-manager' ); ?>"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></button>
                        </div>
                    </p>
                    <p class="login-container">
                        <label for="pass2"><?php esc_html_e( 'Confirm New Password', 'shop-manager' ); ?></label>
                        <div class="pw-wrap">
                            <input type="password" name="pass2" id="pass2" class="login-input" autocomplete="new-password" minlength="8" required>
                            <button type="button" class="pw-toggle" data-target="pass2" aria-label="<?php esc_attr_e( 'Show password', 'shop-manager' ); ?>"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></button>
                        </div>
                    </p>
                    <p class="login-hint"><?php esc_html_e( 'Minimum 8 characters.', 'shop-manager' ); ?></p>
                    <p class="login-submit">
                        <input type="submit" class="login-button" value="<?php esc_attr_e( 'Set Password', 'shop-manager' ); ?>">
                    </p>
                </form>
            </div>
        </div>

    <?php elseif ( $sm_action === 'invalid-key' ) : ?>
        <!-- ── Invalid / Expired Key ── -->
        <div class="wpkin-sm-login-form-wrapper">
            <div class="wpkin-sm-login-form">
                <h2><?php esc_html_e( 'Link Expired', 'shop-manager' ); ?></h2>
                <div class="error-message"><?php echo wp_kses_post( $error_message ); ?></div>
                <p class="login-help">
                    <a href="<?php echo esc_url( $lost_password_url ); ?>"><?php esc_html_e( 'Request a new password reset link', 'shop-manager' ); ?></a>
                </p>
            </div>
        </div>

    <?php elseif ( $sm_action === 'lost-password' ) : ?>
        <!-- ── Forgot Password Form ── -->
        <div class="wpkin-sm-login-form-wrapper">
            <div class="wpkin-sm-login-form">
                <h2><?php esc_html_e( 'Reset Your Password', 'shop-manager' ); ?></h2>
                <?php if ( $error_message ) : ?>
                    <div class="error-message"><?php echo wp_kses_post( $error_message ); ?></div>
                <?php endif; ?>
                <?php if ( $success_message ) : ?>
                    <div class="success-message"><?php echo wp_kses_post( $success_message ); ?></div>
                    <p class="login-help">
                        <a href="<?php echo esc_url( home_url( '/sm-dashboard/' ) ); ?>"><?php esc_html_e( '← Back to login', 'shop-manager' ); ?></a>
                    </p>
                <?php else : ?>
                    <p class="login-description"><?php esc_html_e( 'Enter your username or email address and we\'ll send you a link to reset your password.', 'shop-manager' ); ?></p>
                    <form method="post" action="">
                        <?php wp_nonce_field( 'sm_lost_password_action', 'sm_lost_password_nonce' ); ?>
                        <p class="login-container">
                            <label for="user_login"><?php esc_html_e( 'Username or Email Address', 'shop-manager' ); ?></label>
                            <input type="text" name="user_login" id="user_login" class="login-input" autocomplete="username" required>
                        </p>
                        <p class="login-submit">
                            <input type="submit" class="login-button" value="<?php esc_attr_e( 'Send Reset Link', 'shop-manager' ); ?>">
                        </p>
                    </form>
                    <p class="login-help">
                        <a href="<?php echo esc_url( home_url( '/sm-dashboard/' ) ); ?>"><?php esc_html_e( '← Back to login', 'shop-manager' ); ?></a>
                    </p>
                <?php endif; ?>
            </div>
        </div>

    <?php elseif ( is_user_logged_in() ) : ?>
        <?php
        $user_obj       = wp_get_current_user();
        $roles_to_check = array_merge(
            [ 'administrator', 'shop_manager', 'editor' ],
            \WPKIN_SHOP_MANAGER\Modules\EmployeeManager::get_active_oxi_roles()
        );
        $has_permission = false;
        foreach ( $roles_to_check as $check_role ) {
            if ( in_array( $check_role, $user_obj->roles, true ) ) {
                $has_permission = true;
                break;
            }
        }

        if ( ! $has_permission ) {
            $user_roles     = (array) $user_obj->roles;
            $has_custom_role = false;
            foreach ( $user_roles as $r ) {
                if ( strpos( $r, 'oxi_sm_custom_' ) === 0 ) {
                    $has_custom_role = true;
                    break;
                }
            }

            if ( $has_custom_role ) {
                ?>
                <div class="wpkin-sm-login-form-wrapper">
                    <div class="wpkin-sm-login-form" style="text-align:center;">
                        <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#faad14" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="margin-bottom:16px;"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
                        <h2 style="color:#333;margin-bottom:12px;"><?php esc_html_e( 'Access Restricted', 'shop-manager' ); ?></h2>
                        <p class="login-description"><?php esc_html_e( 'Your account role requires an active Pro license to access this dashboard. The Pro license has expired or is no longer active.', 'shop-manager' ); ?></p>
                        <p class="login-description"><?php esc_html_e( 'Please contact your administrator to restore access.', 'shop-manager' ); ?></p>
                        <p style="margin-top:24px;">
                            <a href="<?php echo esc_url( wp_logout_url( home_url( '/sm-dashboard' ) ) ); ?>" style="color:#4a90e2;font-size:14px;text-decoration:none;"><?php esc_html_e( '← Sign in with a different account', 'shop-manager' ); ?></a>
                        </p>
                    </div>
                </div>
                <?php
                wp_footer();
                exit;
            }

            echo '<div class="wpkin-sm-login-form-wrapper"><div class="wpkin-sm-login-form">';
            echo '<div class="error-message">' . esc_html__( "You don't have the permission to access this page.", 'shop-manager' ) . '</div>';
            echo '</div></div>';
            wp_footer();
            exit;
        }
        ?>
        <div id="wpkin-shop-manager-public"></div>

    <?php else : ?>
        <!-- ── Login Form ── -->
        <div class="wpkin-sm-login-form-wrapper">
            <div class="wpkin-sm-login-form">
                <h2><?php esc_html_e( 'Please log in to access the dashboard', 'shop-manager' ); ?></h2>
                <?php if ( $error_message ) : ?>
                    <div class="error-message"><?php echo wp_kses_post( $error_message ); ?></div>
                <?php endif; ?>
                <?php $current_url = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : ''; ?>
                <form name="loginform" id="loginform" action="<?php echo esc_url( $current_url ); ?>" method="post">
                    <?php wp_nonce_field( 'sm_login_action', 'sm_login_nonce' ); ?>
                    <p class="login-container">
                        <label for="user_login"><?php esc_html_e( 'Username or Email Address', 'shop-manager' ); ?></label>
                        <input type="text" name="log" id="user_login" class="login-input" value="<?php echo esc_attr( isset( $_POST['log'] ) ? sanitize_user( wp_unslash( $_POST['log'] ) ) : '' ); ?>" size="20" autocapitalize="off" autocomplete="username" required>
                    </p>
                    <p class="login-container">
                        <label for="user_pass"><?php esc_html_e( 'Password', 'shop-manager' ); ?></label>
                        <div class="pw-wrap">
                            <input type="password" name="pwd" id="user_pass" class="login-input" value="" size="20" autocomplete="current-password" required>
                            <button type="button" class="pw-toggle" data-target="user_pass" aria-label="<?php esc_attr_e( 'Show password', 'shop-manager' ); ?>"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></button>
                        </div>
                    </p>
                    <p class="login-remember">
                        <label>
                            <input name="rememberme" type="checkbox" id="rememberme" value="forever">
                            <?php esc_html_e( 'Remember Me', 'shop-manager' ); ?>
                        </label>
                    </p>
                    <p class="login-submit">
                        <input type="submit" name="wp-submit" id="wp-submit" class="login-button" value="<?php esc_attr_e( 'Log In', 'shop-manager' ); ?>">
                        <input type="hidden" name="redirect_to" value="<?php echo esc_url( home_url( '/sm-dashboard' ) ); ?>">
                    </p>
                </form>
                <p class="login-help">
                    <a href="<?php echo esc_url( $lost_password_url ); ?>"><?php esc_html_e( 'Forgot your password?', 'shop-manager' ); ?></a>
                </p>
            </div>
        </div>

    <?php endif; ?>
    <?php endif; ?>

    <?php wp_footer(); ?>
    <script>
        document.querySelectorAll('.pw-toggle').forEach(function(btn) {
            btn.addEventListener('click', function() {
                var input = document.getElementById(this.dataset.target);
                var show  = input.type === 'password';
                input.type = show ? 'text' : 'password';
                this.classList.toggle('active', show);
                var svg = this.querySelector('svg');
                if (show) {
                    svg.innerHTML = '<path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"/><path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"/><line x1="1" y1="1" x2="23" y2="23"/>';
                } else {
                    svg.innerHTML = '<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>';
                }
            });
        });
    </script>
</body>
</html>
