@extends('layouts.front')

@section('content')
<div class="jel-portal-page">
    @include('front.partials.flash-messages')

    <section class="jel-profile-layout">
        <div class="jel-profile-intro">
            <span class="jel-portal-kicker">Profile Photo</span>
            <h1>Update your profile picture.</h1>
            <p>Clear profile image se verification, result identity aur wallet-related student review fast ho jata hai. Photo select karke preview dekhiye, phir save kar dijiye.</p>
        </div>

        <section class="jel-profile-card">
            <form class="jel-profile-photo-form" action="{{ route('profileimagesave') }}" method="post">
                @csrf
                <input type="hidden" name="photoid" id="photoid" value="{{ old('photoid', $usersdata->profileimh) }}">

                <div class="jel-profile-photo-preview">
                    <img id="profilePreview" src="{{ $profileImageUrl }}" alt="{{ $usersdata->name }}">
                </div>

                <div class="jel-profile-photo-copy">
                    <h2>{{ $usersdata->name }}</h2>
                    <p>Best result ke liye front-facing, bright aur recent image use kijiye. Supported formats: JPG, PNG, GIF, WEBP.</p>
                </div>

                <div id="uploadStatus" class="jel-upload-loading" hidden></div>

                <div class="jel-profile-photo-actions">
                    <button class="jel-portal-button jel-portal-button-secondary" id="triggerUpload" type="button">Choose New Photo</button>
                    <button class="jel-portal-button" type="submit">Save Profile Photo</button>
                    <a class="jel-portal-button jel-portal-button-muted" href="{{ route('editprofile') }}">Back to Profile</a>
                </div>
            </form>
        </section>
    </section>

    <form id="uploadForm" class="d-none" action="{{ route('student.upload.attachment') }}" method="post" enctype="multipart/form-data">
        @csrf
        <input name="userImage" id="newuploaed" type="file" accept="image/png, image/gif, image/jpeg, image/webp">
        <input type="hidden" name="purpose" value="profile">
    </form>
</div>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    const uploadTrigger = document.getElementById('triggerUpload');
    const fileInput = document.getElementById('newuploaed');
    const uploadForm = document.getElementById('uploadForm');
    const uploadStatus = document.getElementById('uploadStatus');
    const photoIdField = document.getElementById('photoid');
    const previewImage = document.getElementById('profilePreview');
    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');

    if (!uploadTrigger || !fileInput || !uploadForm || !uploadStatus || !photoIdField || !previewImage || !csrfToken) {
        return;
    }

    const setStatus = function (message, state) {
        uploadStatus.hidden = !message;
        uploadStatus.textContent = message || '';
        uploadStatus.dataset.state = state || 'idle';
    };

    uploadTrigger.addEventListener('click', function () {
        fileInput.click();
    });

    fileInput.addEventListener('change', async function () {
        if (!fileInput.files || fileInput.files.length === 0) {
            return;
        }

        setStatus('Uploading image...', 'loading');

        try {
            const response = await fetch(uploadForm.action, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': csrfToken,
                    'X-Requested-With': 'XMLHttpRequest',
                },
                body: new FormData(uploadForm),
            });

            const payload = await response.json();

            if (!response.ok) {
                throw new Error(payload.message || 'Upload failed. Please try again.');
            }

            photoIdField.value = payload.attachment_id || '';

            if (payload.preview_url) {
                previewImage.src = payload.preview_url;
            }

            setStatus('Photo uploaded. Ab save button dabakar profile image update kijiye.', 'success');
        } catch (error) {
            setStatus(error.message || 'Upload failed. Please try again.', 'error');
        }
    });
});
</script>
@endpush
@endsection
