/*
Theme Name: Eduma Child
Theme URI: https://eduma.thimpress.com/
Template: eduma
Author: ThimPress
Author URI: https://thimpress.com
Description: Premium Online LMS &amp; Education WordPress Theme.
Tags: two-columns,three-columns,left-sidebar,right-sidebar,custom-background,custom-header,custom-menu,editor-style,post-formats,rtl-language-support,sticky-post,theme-options,translation-ready,accessibility-ready
Version: 5.6.7.1743705656
Updated: 2025-04-03 18:40:56

*/
function dynamic_teacher_webhook_url() {
    return home_url('/wp-json/custom-api/v1/teacher-register/');
}
add_shortcode('dynamic_teacher_webhook', 'dynamic_teacher_webhook_url');

add_shortcode('show_if_logged_out', function($atts, $content = '') {
    if (!is_user_logged_in()) {
        return do_shortcode($content);
    }
    return ''; // Hide content if logged in
});

add_filter('authenticate', function ($user) {
    if (is_a($user, 'WP_User') && in_array('pending_approval', (array)$user->roles)) {
        return new WP_Error('approval_pending', __('Your instructor application is pending approval by the admin.'));
    }
    return $user;
}, 30);


// Register Custom REST API Endpoint
add_action('elementor_pro/forms/new_record', function ($record, $ajax_handler) {
    if (is_user_logged_in()) {
        return;
    }

    $form_name = $record->get_form_settings('form_name');
    if ('become_a_teacher_form' !== $form_name) {
        return;
    }

    $raw_fields = $record->get('fields');
    $fields = [];
    foreach ($raw_fields as $id => $field) {
        $fields[$id] = $field['value'];
    }

    // Extract and sanitize form data
    $name = sanitize_text_field($fields['full_name'] ?? '');
    $email = sanitize_email($fields['email_address'] ?? '');
    $phone = sanitize_text_field($fields['phone_number'] ?? '');
    $dob = sanitize_text_field($fields['date_of_birth'] ?? '');
    $gender = sanitize_text_field($fields['gender'] ?? '');
    $nationality = sanitize_text_field($fields['nationality'] ?? '');
    $location = sanitize_text_field($fields['current_location'] ?? '');
    $linkedin = esc_url_raw($fields['linkedin_profile'] ?? '');
    $cv_url = esc_url_raw($fields['resume_cv'] ?? '');
    $qualification = sanitize_text_field($fields['highest_qualification'] ?? '');
    $certifications = sanitize_text_field($fields['relevant_certifications'] ?? '');
    $experience_years = intval($fields['teaching_experience'] ?? 0);


    // === Validation ===
    if (empty($email) || empty($name)) {
        $ajax_handler->add_error('email_address', 'Email and Full Name are required.');
        return;
    }

    if (email_exists($email)) {
        $ajax_handler->add_error('email_address', 'This email is already registered.');
        return;
    }

    // Validate Date of Birth: must be a valid date, before today, and user must be at least 18 years old
    $dob_timestamp = strtotime($dob);
    if (!$dob_timestamp) {
        $ajax_handler->add_error('date_of_birth', 'Invalid date format.');
        return;
    }

    $age = (int)floor((time() - $dob_timestamp) / (365.25 * 24 * 60 * 60));
    if ($dob_timestamp >= time()) {
        $ajax_handler->add_error('date_of_birth', 'Date of birth must be before today.');
        return;
    }
    if ($age < 18) {
        $ajax_handler->add_error('date_of_birth', 'You must be at least 18 years old.');
        return;
    }

    // Validate Experience Years: must be between 1 and 40
    if ($experience_years < 1 || $experience_years > 40) {
        $ajax_handler->add_error('teaching_experience', 'Teaching experience must be between 1 and 40 years.');
        return;
    }

    // Store in session for OTP verification
    $_SESSION['lp_pending_teacher'] = [
        'username'    => $email,
        'email'       => $email,
        'name'        => $name,
        'phone'       => $phone,
        'dob'         => $dob,
        'gender'      => $gender,
        'nationality' => $nationality,
        'location'    => $location,
        'linkedin'    => $linkedin,
        'cv_url'      => $cv_url,
        'qualification' => $qualification,
        'certifications' => $certifications,
        'experience_years' => $experience_years,
        'password'    => wp_generate_password(),
        'role'        => 'pending_approval',
        'want_instructor' => true,
    ];

    // Generate and send OTP
    $otp = rand(100000, 999999);
    $_SESSION['lp_teacher_otp_code'] = $otp;
    $_SESSION['lp_teacher_otp_created_at'] = time();

    wp_mail($email, 'Verify Your Email - OTP Inside', "Your OTP code is: $otp\nValid for 10 minutes.");

    // Redirect user to OTP page
    $ajax_handler->add_response_data('redirect_url', home_url('/verify-otp/'));
}, 10, 2);


add_action('admin_init', function () {
    if (!isset($_GET['lp-action']) || !isset($_GET['user_id']) || !isset($_GET['nonce'])) return;

    if (!wp_verify_nonce($_GET['nonce'])) {
        wp_die('Invalid nonce.');
    }

    $user_id = absint($_GET['user_id']);
    $action = sanitize_text_field($_GET['lp-action']);
    $user = get_user_by('id', $user_id);
    if (!$user) return;

    if (!in_array('pending_request', (array) $user->roles)) return;

    if ($action === 'accept-request') {
        $user->set_role('lp_teacher');
        update_user_meta($user_id, '_lp_become_instructor', 'yes');
        update_user_meta($user_id, '_lp_instructor_status', 'approved');
    } elseif ($action === 'deny-request') {
        $user->set_role('subscriber');
        update_user_meta($user_id, '_lp_become_instructor', 'denied');
        update_user_meta($user_id, '_lp_instructor_status', 'denied');
    }

    wp_redirect(remove_query_arg(['lp-action', 'user_id', 'nonce'], wp_get_referer()));
    exit;
});
