<?php

namespace MovieEngine\Frontend\Users;

if (! defined("ABSPATH")) {
    exit; // Exit if accessed directly
}

class ProfileManager {

    public function __construct() {
        add_action('wp_ajax_movie_engine_update_profile', [$this, 'update_profile']);
    }

    public function update_profile() {
        if (!isset($_POST['movie_engine_profile_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['movie_engine_profile_nonce'])), 'movie_engine_update_profile')) {
            wp_send_json_error(['message' => esc_html__('Security check failed', 'cine-movie-engine')]);
        }

        $user_id = get_current_user_id();
        if (!$user_id) {
            wp_send_json_error(['message' => esc_html__('You must be logged in', 'cine-movie-engine')]);
        }

        $display_name = isset($_POST['display_name']) ? sanitize_text_field(wp_unslash($_POST['display_name'])) : '';
        $email = isset($_POST['user_email']) ? sanitize_email(wp_unslash($_POST['user_email'])) : '';
        $first_name = isset($_POST['first_name']) ? sanitize_text_field(wp_unslash($_POST['first_name'])) : '';
        $last_name = isset($_POST['last_name']) ? sanitize_text_field(wp_unslash($_POST['last_name'])) : '';
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        $current_password = isset($_POST['current_password']) ? wp_unslash($_POST['current_password']) : '';
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        $new_password = isset($_POST['new_password']) ? wp_unslash($_POST['new_password']) : '';
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        $confirm_password = isset($_POST['confirm_password']) ? wp_unslash($_POST['confirm_password']) : '';

        if (empty($display_name) || empty($email)) {
            wp_send_json_error(['message' => esc_html__('Display name and email are required', 'cine-movie-engine')]);
        }
        if (!is_email($email)) {
            wp_send_json_error(['message' => esc_html__('Invalid email address', 'cine-movie-engine')]);
        }

        $email_exists = email_exists($email);
        if ($email_exists && $email_exists != $user_id) {
            wp_send_json_error(['message' => esc_html__('This email is already in use', 'cine-movie-engine')]);
        }
        $user_data = [
            'ID' => $user_id,
            'display_name' => $display_name,
            'user_email' => $email,
        ];

        if (!empty($new_password)) {
            /**
             * Allow Pro plugin to customize password validation for social login users
             * 
             * @param bool|WP_Error $validation_result False to use default validation, WP_Error to return error, true to skip validation
             * @param int $user_id Current user ID
             * @param string $current_password Current password from form
             * @param string $new_password New password from form
             */
            $custom_validation = apply_filters('movie_engine_validate_password_change', false, $user_id, $current_password, $new_password);

            if (is_wp_error($custom_validation)) {
                wp_send_json_error(['message' => $custom_validation->get_error_message()]);
            }

            // If Pro plugin didn't handle validation, use default
            if ($custom_validation !== true) {
                $user = get_userdata($user_id);
                if (empty($current_password) || !wp_check_password($current_password, $user->user_pass, $user_id)) {
                    wp_send_json_error(['message' => esc_html__('Current password is incorrect', 'cine-movie-engine')]);
                }
            }

            if ($new_password !== $confirm_password) {
                wp_send_json_error(['message' => esc_html__('Passwords do not match', 'cine-movie-engine')]);
            }

            if (strlen($new_password) < 8) {
                wp_send_json_error(['message' => esc_html__('Password must be at least 8 characters', 'cine-movie-engine')]);
            }

            $user_data['user_pass'] = $new_password;
        }

        $updated = wp_update_user($user_data);

        if (is_wp_error($updated)) {
            wp_send_json_error(['message' => $updated->get_error_message()]);
        }

        update_user_meta($user_id, 'first_name', $first_name);
        update_user_meta($user_id, 'last_name', $last_name);

        $avatar_url = null;
        if (isset($_FILES['avatar']) && !empty($_FILES['avatar']['name'])) {
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            $avatar_result = $this->upload_avatar($user_id, $_FILES['avatar']);
            if (is_wp_error($avatar_result)) {
                wp_send_json_error(['message' => $avatar_result->get_error_message()]);
            }
            $avatar_url = $avatar_result;
        }

        wp_send_json_success([
            'message' => esc_html__('Profile updated successfully!', 'cine-movie-engine'),
            'display_name' => $display_name,
            'avatar_url' => $avatar_url,
        ]);
    }


    private function upload_avatar($user_id, $file) {
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        require_once(ABSPATH . 'wp-admin/includes/media.php');

        if ($file['size'] > 2 * 1024 * 1024) {
            return new \WP_Error('file_too_large', esc_html__('File size must be less than 2MB', 'cine-movie-engine'));
        }

        $upload_overrides = [
            'test_form' => false,
            'mimes'     => [
                'jpg|jpeg|jpe' => 'image/jpeg',
                'gif'          => 'image/gif',
                'png'          => 'image/png',
                'webp'         => 'image/webp'
            ],
            'test_type' => true
        ];

        $upload = wp_handle_upload($file, $upload_overrides);

        if (isset($upload['error'])) {
            return new \WP_Error('upload_error', $upload['error']);
        }

        update_user_meta($user_id, 'movie_engine_avatar_url', $upload['url']);

        return $upload['url'];
    }
}
