<?php
if (isset($_GET["vend"]) && $_GET["vend"] == "account") {
    $id = get_current_user_id();
    $wp_user = get_userdata($id);
    $users = new Users();
    $user_data = $users->getUser($id, false, true); // Get VTUPress User Object
    
    // Fallbacks
    $first_name = $user_data->first_name ?? $wp_user->first_name;
    $last_name = $user_data->last_name ?? $wp_user->last_name;
    $email = $wp_user->user_email;
    $phone = $user_data->phone ?? '';
    $pin = $user_data->pin ?? '';
    $about = $user_data->about ?? '';
    $photo = $user_data->photo ?? '';
    $apikey = $user_data->apikey ?? 'Not Generated';

    // Image Fallback
    if (empty($photo)) {
        $photo = 'https://via.placeholder.com/150';
    }
?>

<div class="container py-4">
    <div class="row">
        <!-- Profile Sidebar -->
        <div class="col-md-4 mb-3">
            <div class="card text-center shadow">
                <div class="card-body">
                    <form id="photo-form">
                        <div class="position-relative d-inline-block">
                            <img src="<?php echo esc_url($photo); ?>" id="profile-preview" class="rounded-circle mb-3" style="width: 150px; height: 150px; object-fit: cover; border: 3px solid #eee;">
                            <label for="photo-upload" class="position-absolute bottom-0 end-0 bg-primary text-white rounded-circle p-2 pointer" style="cursor: pointer;">
                                <i class="fa fa-camera"></i>
                            </label>
                            <input type="file" id="photo-upload" name="photo_upload" class="d-none" accept="image/*">
                        </div>
                    </form>
                    
                    <h5 class="card-title"><?php echo esc_html(ucfirst($first_name) . ' ' . ucfirst($last_name)); ?></h5>
                    <p class="text-muted"><?php echo esc_html($email); ?></p>
                    
                    <div class="form-group mb-3 text-start">
                         <label class="small text-muted">About Me</label>
                         <textarea class="form-control" id="about-input" rows="3" placeholder="Tell us about yourself..."><?php echo esc_textarea($about); ?></textarea>
                    </div>
                </div>
            </div>
            
             <!-- API Key Section -->
            <div class="card shadow mt-3">
                <div class="card-header bg-dark text-white">
                    <h6 class="mb-0"><i class="fa fa-key"></i> API Key</h6>
                </div>
                <div class="card-body">
                    <div class="input-group mb-3">
                        <input type="text" class="form-control" id="api-key-input" value="<?php echo esc_attr($apikey); ?>" readonly>
                        <button class="btn btn-outline-secondary" type="button" onclick="copyToClipboard('#api-key-input')">
                            <i class="fa fa-copy"></i>
                        </button>
                    </div>
                    <button class="btn btn-warning w-100 btn-sm" id="generate-key-btn">
                        <i class="fa fa-sync"></i> Generate New Key
                    </button>
                </div>
            </div>
        </div>

        <!-- Account Settings -->
        <div class="col-md-8">
            <div class="card shadow">
                <div class="card-header bg-white">
                    <h4 class="card-title mb-0">Account Settings</h4>
                </div>
                <div class="card-body">
                    <form id="profile-form">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">First Name</label>
                                <input type="text" class="form-control" name="first_name" value="<?php echo esc_attr($first_name); ?>" <?php echo !empty($first_name) ? 'readonly' : ''; ?>>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Last Name</label>
                                <input type="text" class="form-control" name="last_name" value="<?php echo esc_attr($last_name); ?>" <?php echo !empty($last_name) ? 'readonly' : ''; ?>>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Email Address</label>
                            <input type="email" class="form-control" name="email" value="<?php echo esc_attr($email); ?>">
                            <small class="text-muted">Changing this will update your login email.</small>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Phone Number</label>
                            <input type="number" class="form-control" name="phone" value="<?php echo esc_attr($phone); ?>">
                        </div>

                        <hr>
                        <h6 class="mb-3 text-muted">Security</h6>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">New Password</label>
                                <input type="password" class="form-control" name="password" placeholder="Leave empty to keep current">
                            </div>
                             <div class="col-md-6 mb-3">
                                <label class="form-label">Transaction PIN</label>
                                <input type="password" class="form-control" name="pin" value="<?php echo esc_attr($pin); ?>" placeholder="Enter 4-digit PIN">
                            </div>
                        </div>

                        <div class="text-end">
                            <button type="button" class="btn btn-primary" id="save-profile-btn">
                                <i class="fa fa-save"></i> Save Changes
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    
    // Photo Preview
    $('#photo-upload').change(function(){
        const file = this.files[0];
        if (file){
            let reader = new FileReader();
            reader.onload = function(event){
                $('#profile-preview').attr('src', event.target.result);
            }
            reader.readAsDataURL(file);
        }
    });

    // Save Profile
    $('#save-profile-btn').click(function() {
        var btn = $(this);
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Saving...');

        var formData = new FormData($('#profile-form')[0]);
        // Append other fields
        formData.append('action', 'vtupress_update_profile');
        formData.append('about', $('#about-input').val());
        formData.append('nonce', '<?php echo wp_create_nonce("vtupress_user_nonce"); ?>');

        // Append Photo
        var photo = $('#photo-upload')[0].files[0];
        if(photo) {
            formData.append('photo_upload', photo);
        }

        $.ajax({
            url: '<?php echo admin_url("admin-ajax.php"); ?>',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function(res) {
                btn.prop('disabled', false).html('<i class="fa fa-save"></i> Save Changes');
                if(res.status === 'success') {
                    Swal.fire('Success', res.message, 'success').then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire('Error', res.message, 'error');
                }
            },
            error: function(err) {
                 btn.prop('disabled', false).html('<i class="fa fa-save"></i> Save Changes');
                 Swal.fire('Error', 'Server Error', 'error');
            }
        });
    });

    // Generate API Key
    $('#generate-key-btn').click(function() {
        Swal.fire({
            title: 'Generate New Key?',
            text: "This will invalidate your old API key.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, generate new'
        }).then((result) => {
            if (result.isConfirmed) {
                $.post('<?php echo admin_url("admin-ajax.php"); ?>', {
                    action: 'vtupress_generate_apikey',
                    nonce: '<?php echo wp_create_nonce("vtupress_user_nonce"); ?>'
                }, function(res) {
                    if(res.status === 'success') {
                         $('#api-key-input').val(res.apikey);
                         Swal.fire('Generated!', 'Your new API key is ready.', 'success');
                    } else {
                        Swal.fire('Error', res.message, 'error');
                    }
                });
            }
        });
    });

    // Copy to Clipboard Helper
    window.copyToClipboard = function(selector) {
        var copyText = $(selector);
        copyText.select();
        document.execCommand("copy");
        Swal.fire({
             toast: true,
             icon: 'success',
             title: 'Copied!',
             position: 'top-end',
             showConfirmButton: false,
             timer: 1500
        });
    }
});
</script>

<?php
}
?>