<?php
// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Get current user information
$current_user = wp_get_current_user();
$user_id = get_current_user_id();
$first_name = get_user_meta($user_id, 'first_name', true);
$last_name = get_user_meta($user_id, 'last_name', true);
$user_email = $current_user->user_email;
$user_login = $current_user->user_login;
$user_phone = get_user_meta($user_id, 'billing_phone', true);
// Get user avatar URL
    $avatar_url = kavehboard_get_user_avatar_url($user_id, 189);

// Handle form submission
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Handle avatar upload
    if (isset($_POST['upload_avatar']) && wp_verify_nonce($_POST['avatar_nonce'], 'upload_avatar_action')) {
        if (!empty($_FILES['avatar_file']['name'])) {
            $uploaded_file = $_FILES['avatar_file'];
            
            // Check file type
            $allowed_types = array('image/jpeg', 'image/jpg', 'image/png', 'image/gif');
            if (in_array($uploaded_file['type'], $allowed_types)) {
                
                // Check file size (max 2MB)
                if ($uploaded_file['size'] <= 2097152) {
                    
                    require_once(ABSPATH . 'wp-admin/includes/file.php');
                    require_once(ABSPATH . 'wp-admin/includes/image.php');
                    require_once(ABSPATH . 'wp-admin/includes/media.php');
                    
                    $upload_overrides = array('test_form' => false);
                    $movefile = wp_handle_upload($uploaded_file, $upload_overrides);
                    
                    if ($movefile && !isset($movefile['error'])) {
                        // Create attachment
                        $attachment = array(
                            'post_mime_type' => $uploaded_file['type'],
                            'post_title' => sanitize_file_name($uploaded_file['name']),
                            'post_content' => '',
                            'post_status' => 'inherit'
                        );
                        
                        $attach_id = wp_insert_attachment($attachment, $movefile['file']);
                        $attach_data = wp_generate_attachment_metadata($attach_id, $movefile['file']);
                        wp_update_attachment_metadata($attach_id, $attach_data);
                        
                        // Update user avatar
                        update_user_meta($user_id, 'custom_avatar', $attach_id);
                        $success_message = __('Your profile image has been successfully updated.', 'kavehTheme');
                        
                        // Update avatar URL
                        $avatar_url = kavehboard_get_user_avatar_url($user_id, 189);
                    } else {
                        $error_message = __('File upload error: ', 'kavehTheme') . $movefile['error'];
                    }
                } else {
                    $error_message = __('File size should not exceed 2 MB.', 'kavehTheme');
                }
            } else {
                $error_message = __('File format is not allowed. Only JPG, PNG and GIF are allowed.', 'kavehTheme');
            }
        } else {
            $error_message = __('Please select a file.', 'kavehTheme');
        }
    }
    
    // Handle profile update
    if (isset($_POST['update_profile']) && wp_verify_nonce($_POST['profile_nonce'], 'update_profile_action')) {
        $new_first_name = sanitize_text_field($_POST['first_name']);
        $new_last_name = sanitize_text_field($_POST['last_name']);
        $new_email = sanitize_email($_POST['email']);
        $new_phone = sanitize_text_field($_POST['phone']);
        $new_display_name = sanitize_text_field($_POST['display_name']);
        
        // Update user meta
        $updated = wp_update_user(array(
            'ID' => $user_id,
            'first_name' => $new_first_name,
            'last_name' => $new_last_name,
            'user_email' => $new_email,
            'display_name' => $new_display_name
        ));
        
        if (!is_wp_error($updated)) {
            update_user_meta($user_id, 'billing_phone', $new_phone);
            $success_message = __('Your information has been successfully updated.', 'kavehTheme');
            
            // Update local variables
            $first_name = $new_first_name;
            $last_name = $new_last_name;
            $user_email = $new_email;
            $user_phone = $new_phone;
        } else {
            $error_message = __('Error updating information: ', 'kavehTheme') . $updated->get_error_message();
        }
    }
    
    // Handle password change
    if (isset($_POST['change_password']) && wp_verify_nonce($_POST['password_nonce'], 'change_password_action')) {
        $current_password = $_POST['current_password'];
        $new_password = $_POST['new_password'];
        $confirm_password = $_POST['confirm_password'];
        
        // Verify current password
        if (!wp_check_password($current_password, $current_user->user_pass, $user_id)) {
            $error_message = __('Current password is incorrect.', 'kavehTheme');
        } elseif ($new_password !== $confirm_password) {
            $error_message = __('New password and confirmation do not match.', 'kavehTheme');
        } elseif (strlen($new_password) < 6) {
            $error_message = __('Password must be at least 6 characters.', 'kavehTheme');
        } else {
            // Update password
            wp_set_password($new_password, $user_id);
            $success_message = __('Your password has been successfully changed.', 'kavehTheme');
        }
    }
}
?>

<!-- Start Content -->
<div class="dashboard-kaveh-content">

        
        <?php if (!empty($success_message)): ?>
        <div class="col-12">
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo esc_html($success_message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        </div>
        <?php endif; ?>
        
        <?php if (!empty($error_message)): ?>
        <div class="col-12">
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo esc_html($error_message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        </div>
        <?php endif; ?>
        
        <div class="dashboard-kaveh-profile">
            <!-- Start Heading -->
            <div class="dashboard-kaveh-profile-heading d-flex align-items-md-center flex-column flex-md-row">
                <div class="title d-flex align-items-center flex-fill flex-grow-0 flex-shrink-0">
                    <i class="icon-user-edit-2 lh-1 position-relative"></i>
                    <?php _e('User Information', 'kavehTheme'); ?>
                </div>
            </div>
            <!-- End Heading -->
            <div class="dashboard-kaveh-profile-row d-flex flex-wrap">
                <!-- Start Change Image -->
                <div class="dashboard-kaveh-profile-row-right w-100 flex-fill flex-grow-0 flex-shrink-0">
                    <div class="dashboard-kaveh-profile-change-image">
                        <img src="<?php echo esc_url($avatar_url); ?>" alt="avatar" width="189" height="187" class="w-100 d-block">
                        <form method="post" action="" enctype="multipart/form-data">
                            <?php wp_nonce_field('upload_avatar_action', 'avatar_nonce'); ?>
                            <label class="d-block w-100 text-center fw-bold">
                                <input type="file" name="avatar_file" accept="image/*" hidden onchange="this.form.submit()">
                                <input type="hidden" name="upload_avatar" value="1">
                                <?php _e('Edit Image', 'kavehTheme'); ?>
                            </label>
                        </form>
                    </div>
                </div>
                <!-- End Change Image -->
                <!-- Start Form -->
                <div class="dashboard-kaveh-profile-row-left w-100 flex-fill flex-grow-0 flex-shrink-0">
                    <div class="dashboard-kaveh-profile-form">
                        <form method="post" action="">
                            <?php wp_nonce_field('update_profile_action', 'profile_nonce'); ?>
                            <div class="row">
                                <div class="col-sm-6">
                                    <div class="position-relative">
                                        <label for="firstname" class="d-inline-block fw-bold"><?php _e('First Name', 'kavehTheme'); ?></label>
                                        <input type="text" name="first_name" id="firstname" class="form-control" value="<?php echo esc_attr($first_name); ?>">
                                    </div>
                                </div>
                                <div class="col-sm-6">
                                    <div class="position-relative">
                                        <label for="lastname" class="d-inline-block fw-bold"><?php _e('Last Name', 'kavehTheme'); ?></label>
                                        <input type="text" name="last_name" id="lastname" class="form-control" value="<?php echo esc_attr($last_name); ?>">
                                    </div>
                                </div>
                                <div class="col-sm-6">
                                    <div class="position-relative">
                                        <label for="viewname" class="d-inline-block fw-bold"><?php _e('Display Name', 'kavehTheme'); ?></label>
                                        <input type="text" name="display_name" id="viewname" class="form-control" value="<?php echo esc_attr($current_user->display_name); ?>">
                                    </div>
                                </div>
                                <div class="col-sm-6">
                                    <div class="position-relative">
                                        <label for="email" class="d-inline-block fw-bold"><?php _e('Email', 'kavehTheme'); ?></label>
                                        <input type="email" name="email" id="email" class="form-control" value="<?php echo esc_attr($user_email); ?>">
                                    </div>
                                </div>
                                <div class="col-sm-6">
                                    <div class="position-relative">
                                        <label for="username" class="d-inline-block fw-bold"><?php _e('Username', 'kavehTheme'); ?></label>
                                        <input type="text" name="username" id="username" class="form-control" value="<?php echo esc_attr($user_login); ?>" disabled>
                                    </div>
                                </div>
                                <div class="col-sm-6">
                                    <div class="position-relative">
                                        <label for="phone" class="d-inline-block fw-bold"><?php _e('Mobile Number', 'kavehTheme'); ?></label>
                                        <input type="tel" name="phone" id="phone" class="form-control" value="<?php echo esc_attr($user_phone); ?>">
                                    </div>
                                </div>
                                <div class="col-12">
                                    <button type="submit" name="update_profile" class="btn btn-send btn-black ms-auto text-center mt-3 mt-sm-5 fw-bold d-block"><?php _e('Submit Form', 'kavehTheme'); ?></button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <!-- End Form -->
            </div>
            <!-- Start Change Password -->
            <div class="dashboard-kaveh-profile-change-password">
                <!-- Start Heading -->
                <div class="dashboard-kaveh-profile-change-password-heading d-flex align-items-sm-center justify-content-sm-between gap-3 gap-sm-2 flex-column flex-sm-row">
                    <div class="text d-flex align-items-center">
                        <i class="icon-user-edit-2 lh-1 position-relative"></i>
                        <?php _e('Change your password from this section', 'kavehTheme'); ?>
                    </div>
                    <button type="button" class="btn btn-blue d-flex align-items-center justify-content-between justify-content-sm-center fw-bold">
                        <?php _e('Forgot Password', 'kavehTheme'); ?>
                        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none" viewBox="0 0 20 20">
                            <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" stroke-width="1.5" d="M7.975 4.942 2.917 10l5.058 5.058"/>
                            <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" stroke-width="1.5" d="M17.083 10H3.058" opacity=".4"/>
                        </svg>
                    </button>
                </div>
                <!-- End Heading -->
                <form method="post" action="">
                    <?php wp_nonce_field('change_password_action', 'password_nonce'); ?>
                    <div class="row">
                        <div class="col-sm-6 col-md-4">
                            <div class="position-relative">
                                <label for="currentPassword" class="d-inline-block fw-bold"><?php _e('Current Password', 'kavehTheme'); ?></label>
                                <input type="password" name="current_password" id="currentPassword" class="form-control">
                            </div>
                        </div>
                        <div class="col-sm-6 col-md-4">
                            <div class="position-relative">
                                <label for="newPassword" class="d-inline-block fw-bold"><?php _e('New Password', 'kavehTheme'); ?></label>
                                <input type="password" name="new_password" id="newPassword" class="form-control">
                            </div>
                        </div>
                        <div class="col-12 col-md-4">
                            <div class="position-relative">
                                <label for="confirmPassword" class="d-inline-block fw-bold"><?php _e('Confirm Password', 'kavehTheme'); ?></label>
                                <input type="password" name="confirm_password" id="confirmPassword" class="form-control">
                            </div>
                        </div>
                        <div class="col-12">
                            <button type="submit" name="change_password" class="btn btn-send btn-black ms-auto text-center mt-3 mt-sm-5 fw-bold d-block"><?php _e('Submit Form', 'kavehTheme'); ?></button>
                        </div>
                    </div>
                </form>
            </div>
            <!-- End Change Password -->
        </div>
</div>
<!-- End Content -->