<?php
/*
Template Name: Custom Sign In
*/
if ( ! defined( 'ABSPATH' ) ) exit;
get_header();

// Process POST
$errors = array();
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
    // Verify nonce
    if ( ! isset( $_POST['signin_nonce'] ) || ! wp_verify_nonce( $_POST['signin_nonce'], 'signin_action' ) ) {
        $errors[] = 'Security check failed.';
    } else {
        $username = sanitize_text_field( $_POST['username'] ?? '' );
        $password = $_POST['password'] ?? '';

        if ( empty( $username ) || empty( $password ) ) {
            $errors[] = 'Enter both username and password.';
        } else {
            $creds = array(
                'user_login'    => $username,
                'user_password' => $password,
                'remember'      => isset($_POST['remember']) ? true : false,
            );
            $user = wp_signon( $creds, is_ssl() );
            if ( is_wp_error( $user ) ) {
                $errors[] = $user->get_error_message();
            } else {
                wp_safe_redirect( home_url() ); exit;
            }
        }
    }
}
?>

<div class="signin-container" role="main">
  <h1>Sign in</h1>

  <?php if ( ! empty( $errors ) ) : ?>
    <div class="signin-errors" aria-live="polite">
      <ul>
        <?php foreach ( $errors as $e ) : ?>
          <li><?php echo esc_html( $e ); ?></li>
        <?php endforeach; ?>
      </ul>
    </div>
  <?php endif; ?>

  <form method="post" class="signin-form" novalidate>
    <?php wp_nonce_field( 'signin_action', 'signin_nonce' ); ?>

    <label for="signin-username">Email or username</label>
    <input id="signin-username" name="username" type="text" required autocomplete="username" />

    <label for="signin-password">Password</label>
    <input id="signin-password" name="password" type="password" required autocomplete="current-password" />

    <label class="signin-remember">
      <input name="remember" type="checkbox" /> Remember me
    </label>

    <button type="submit">Sign in</button>
  </form>

  <p><a href="<?php echo wp_lostpassword_url(); ?>">Forgot password?</a></p>
</div>

<?php get_footer(); ?>