<?php

if (!defined('ABSPATH')) exit;

class DevsAccounting_Auth {
    public function __construct() {
        add_action('init', [$this, 'process_authentication']);
        add_action('admin_post_nopriv_devsaccounting_register', [$this, 'handle_registration']);
    }

    public function process_authentication() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (isset($_POST['devsaccounting_login'])) {
                $this->handle_login();
            } elseif (isset($_POST['devsaccounting_register'])) {
                $this->handle_registration();
            }
        }
    }

    public function handle_login() {
        if ( ! wp_verify_nonce( isset( $_POST['dac_login_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['dac_login_nonce'] ) ) : '', 'dac_login_action' ) ) {
            wp_die( 'Security check failed.' );
        }
        $creds = array(
            'user_login'    => sanitize_text_field($_POST['log']),
            'user_password' => sanitize_text_field($_POST['pwd']),
            'remember'      => isset($_POST['remember']) ? true : false
        );

        $user = wp_signon($creds, false);

        $settings = get_option('devsaccounting_settings');
        $settings = json_decode($settings, true);
        if (!is_wp_error($user)) {
            wp_set_current_user($user->ID);
            wp_set_auth_cookie($user->ID);

            wp_safe_redirect(home_url($settings['profile_page']));
            exit();
        } else {
            wp_die('<p class="error">Error: ' . esc_html( $user->get_error_message() ) . '</p>');
        }
    }

    public function handle_registration() {
        if ( ! wp_verify_nonce( isset( $_POST['dac_register_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['dac_register_nonce'] ) ) : '', 'dac_register_action' ) ) {
            wp_die( 'Security check failed.' );
        }
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            wp_die('Invalid request method.');
        }
        $settings = get_option('devsaccounting_settings');
        $settings = json_decode($settings, true);
        $username = sanitize_user($_POST['username']);
        $email = sanitize_email($_POST['email']);
        $password = $_POST['password'];

        if (empty($username) || empty($email) || empty($password)) {
            wp_die('Error: All fields are required.');
        }

        if (username_exists($username) || email_exists($email)) {
            wp_die('Error: Username or Email already exists.');
        }

        $userdata = array(
            'user_login' => $username,
            'user_email' => $email,
            'user_pass'  => $password,
            'role'       => 'subscriber'
        );

        $user_id = wp_insert_user($userdata);

        if (is_wp_error($user_id)) {
            wp_die('Error: ' . esc_html( $user_id->get_error_message() ));
        }
        
        $creds = array(
            'user_login'    => $username,
            'user_password' => $password,
            'remember'      => true
        );

        $user = wp_signon($creds, false);

        if (!is_wp_error($user)) {
            wp_set_current_user($user->ID);
            wp_set_auth_cookie($user->ID);
            wp_safe_redirect(home_url($settings['profile_page']));
            exit();
        } else {
            wp_die('Error logging in: ' . esc_html( $user->get_error_message() ));
        }
    }
}

// Instantiate the class
new DevsAccounting_Auth();
