@extends('layouts.master')
@section('title', 'User Profile')
@section('content')

@include('partials.qi-styles')

<style>
    .border-left-primary {
        border-left: 0.25rem solid #018ca3 !important;
    }
    .border-left-success {
        border-left: 0.25rem solid #419a40 !important;
    }
    .border-left-info {
        border-left: 0.25rem solid #36b9cc !important;
    }
    #dropzone:hover {
        background-color: #f8f9fc;
        border-color: #018ca3 !important;
    }
    .accordion-button:not(.collapsed) {
        color: #018ca3;
        background-color: #e6f7fa;
        box-shadow: inset 0 -1px 0 rgba(0,0,0,.125);
    }
</style>

<div class="qi-wrap container-fluid py-3">
    <!-- Breadcrumb -->
    <div class="qi-bc">
        <a href="{{ route('home') }}">Home</a>
        <i class="fas fa-chevron-right" style="font-size: 0.75rem;"></i>
        <span class="qi-bc-current">User Profile</span>
    </div>

    <!-- Hero Banner -->
    <div class="qi-hero">
        <div>
            <h1>User Profile</h1>
            <p>Manage your account settings, profile picture, and view recent activities.</p>
        </div>
        <div class="d-none d-md-flex align-items-center gap-3">
            <div class="qi-badge">
                <div class="qi-badge-val">{{ $customerDocsCount }}</div>
                <div class="qi-badge-lab">Sales Docs</div>
            </div>
            <div class="qi-badge">
                <div class="qi-badge-val">{{ $supplierDocsCount }}</div>
                <div class="qi-badge-lab">Purchase Docs</div>
            </div>
        </div>
    </div>

    <!-- Feedback Alerts -->
    @if(session('success'))
        <div class="alert alert-success alert-dismissible fade show shadow-sm" role="alert">
            <i class="fas fa-check-circle me-2"></i> {{ session('success') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    @endif

    @if($errors->any())
        <div class="alert alert-danger alert-dismissible fade show shadow-sm" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i> <strong>Please correct the following errors:</strong>
            <ul class="mb-0 mt-2">
                @foreach($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    @endif

    <!-- Statistics Cards -->
    <div class="row mb-4">
        <!-- Customer Docs Card -->
        <div class="col-md-4 mb-3">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-uppercase mb-1" style="color: #018ca3; font-size: 0.75rem;">
                                Customer Docs Created
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $customerDocsCount }}</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-file-invoice fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Supplier Docs Card -->
        <div class="col-md-4 mb-3">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-uppercase mb-1" style="color: #419a40; font-size: 0.75rem;">
                                Supplier Docs Created
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $supplierDocsCount }}</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-file-invoice-dollar fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Receipts Card -->
        <div class="col-md-4 mb-3">
            <div class="card border-left-info shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-uppercase mb-1 text-info" style="font-size: 0.75rem;">
                                Receipts Processed
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $receiptsCount }}</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-receipt fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content Layout Grid -->
    <div class="row">
        <!-- Left Sidebar: Avatar & Recent Activity -->
        <div class="col-lg-4 mb-4">
            <!-- Avatar Upload Card -->
            <div class="card shadow mb-4">
                <div class="card-header py-3 bg-white text-center">
                    <h6 class="m-0 font-weight-bold" style="color: #018ca3;"><i class="fas fa-camera me-2"></i>Profile Photo</h6>
                </div>
                <div class="card-body text-center">
                    <div class="d-flex flex-column align-items-center">
                        <!-- Photo Preview Container -->
                        <div id="avatar-container" class="position-relative mb-3">
                            @if($user->profile_picture)
                                <img id="avatar-preview" src="{{ asset('storage/' . $user->profile_picture) }}" class="rounded-circle border shadow" style="width: 150px; height: 150px; object-fit: cover;">
                            @else
                                @php
                                    $words = explode(' ', $user->name);
                                    $initials = '';
                                    foreach ($words as $word) {
                                        $initials .= strtoupper(substr($word, 0, 1));
                                    }
                                    $initials = substr($initials, 0, 2);
                                @endphp
                                <span id="avatar-initials" class="qi-initials-avatar-lg">{{ $initials ?: 'U' }}</span>
                                <img id="avatar-preview" class="rounded-circle border shadow d-none" style="width: 150px; height: 150px; object-fit: cover;">
                            @endif
                            
                            <!-- Upload Loading Overlay -->
                            <div id="upload-spinner" class="position-absolute top-0 start-0 w-100 h-100 rounded-circle d-none" style="background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 10;">
                                <div class="spinner-border text-light" role="status"></div>
                            </div>
                        </div>
                        
                        <p class="text-muted small">Drag & drop your photo or click below to browse</p>
                        
                        <!-- Photo Form / Dropzone -->
                        <form id="avatar-form" action="{{ route('profile.photo') }}" method="POST" enctype="multipart/form-data" class="w-100">
                            @csrf
                            <!-- Hidden File Input -->
                            <input type="file" name="profile_picture" id="profile_picture" class="d-none" accept="image/*">
                            
                            <!-- Dropzone zone element -->
                            <div id="dropzone" class="border rounded p-3 mb-2" style="border-style: dashed !important; border-color: #d1d3e2 !important; cursor: pointer; transition: background 0.2s;">
                                <i class="fas fa-cloud-upload-alt fa-2x mb-2" style="color: #858796;"></i>
                                <div class="font-weight-bold text-secondary">Upload Image</div>
                            </div>
                            
                            <div id="upload-status" class="alert d-none small p-2"></div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Recent Documents Card -->
            <div class="card shadow mb-4">
                <div class="card-header py-3 bg-white">
                    <h6 class="m-0 font-weight-bold" style="color: #018ca3;"><i class="fas fa-history me-2"></i>Recent Activity</h6>
                </div>
                <div class="card-body p-0">
                    @if($recentDocuments->isEmpty())
                        <div class="qi-empty">No recent documents created.</div>
                    @else
                        <div class="list-group list-group-flush" style="font-size: 0.88rem;">
                            @foreach($recentDocuments as $doc)
                                <div class="list-group-item p-3">
                                    <div class="d-flex w-100 justify-content-between align-items-center mb-1">
                                        <span class="font-weight-bold text-dark">{{ $doc['number'] }}</span>
                                        <small class="text-muted">{{ $doc['date'] }}</small>
                                    </div>
                                    <div class="d-flex w-100 justify-content-between align-items-center">
                                        <span class="text-secondary small">{{ $doc['type'] }}</span>
                                        <span class="font-weight-bold" style="color: #419a40;">${{ number_format($doc['amount'], 2) }}</span>
                                    </div>
                                    <div class="mt-2">
                                        @php
                                            $statusClass = 'qi-status-draft';
                                            if ($doc['status'] === 'processed' || $doc['status'] === 'paid') {
                                                $statusClass = 'qi-status-processed';
                                            } elseif ($doc['status'] === 'converted') {
                                                $statusClass = 'qi-status-converted';
                                            } elseif ($doc['status'] === 'cancelled') {
                                                $statusClass = 'qi-status-cancelled';
                                            }
                                        @endphp
                                        <span class="qi-status {{ $statusClass }}" style="font-size: 0.7rem; padding: 0.1rem 0.4rem;">{{ $doc['status'] }}</span>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    @endif
                </div>
            </div>
        </div>

        <!-- Right Side: Details forms -->
        <div class="col-lg-8 mb-4">
            <!-- Profile Details Form Card -->
            <div class="card shadow mb-4">
                <div class="card-header py-3 bg-white">
                    <h6 class="m-0 font-weight-bold" style="color: #018ca3;"><i class="fas fa-user-edit me-2"></i>Update Profile Details</h6>
                </div>
                <div class="card-body">
                    <form action="{{ route('profile.update') }}" method="POST">
                        @csrf
                        @method('PUT')
                        
                        <h6 class="font-weight-bold text-secondary border-bottom pb-2 mb-3">Basic Information</h6>
                        <div class="row mb-3">
                           <div class="col-md-6 mb-3 mb-md-0">
                               <label for="name" class="form-label font-weight-bold">Display Name <span class="text-danger">*</span></label>
                               <input type="text" name="name" id="name" class="form-control shadow-sm" value="{{ old('name', $user->name) }}" required>
                           </div>
                           <div class="col-md-6">
                               <label for="fullname" class="form-label font-weight-bold">Full Name (Detailed)</label>
                               <input type="text" name="fullname" id="fullname" class="form-control shadow-sm" value="{{ old('fullname', $details->fullname) }}">
                           </div>
                        </div>

                        <div class="row mb-3">
                           <div class="col-md-6 mb-3 mb-md-0">
                               <label for="email" class="form-label font-weight-bold">Email Address <span class="text-danger">*</span></label>
                               <input type="email" name="email" id="email" class="form-control shadow-sm" value="{{ old('email', $user->email) }}" required>
                           </div>
                           <div class="col-md-6">
                               <label for="username" class="form-label font-weight-bold">Username</label>
                               <input type="text" name="username" id="username" class="form-control shadow-sm" value="{{ old('username', $details->username) }}">
                           </div>
                        </div>

                        <div class="row mb-3">
                           <div class="col-md-6 mb-3 mb-md-0">
                               <label for="phone" class="form-label font-weight-bold">Phone Number</label>
                               <input type="text" name="phone" id="phone" class="form-control shadow-sm" value="{{ old('phone', $user->phone) }}">
                           </div>
                           <div class="col-md-6">
                               <label for="national_id" class="form-label font-weight-bold">National ID</label>
                               <input type="text" name="national_id" id="national_id" class="form-control shadow-sm" value="{{ old('national_id', $user->national_id) }}">
                           </div>
                        </div>

                        <div class="mb-4">
                           <label for="address" class="form-label font-weight-bold">Physical Address</label>
                           <textarea name="address" id="address" class="form-control shadow-sm" rows="2">{{ old('address', $user->address) }}</textarea>
                        </div>

                        <!-- Collapsible Password section -->
                        <div class="accordion mb-4" id="passwordAccordion">
                           <div class="accordion-item border rounded shadow-sm">
                               <h2 class="accordion-header" id="headingPassword">
                                   <button class="accordion-button collapsed font-weight-bold text-dark" type="button" data-bs-toggle="collapse" data-toggle="collapse" data-bs-target="#collapsePassword" data-target="#collapsePassword" aria-expanded="false" aria-controls="collapsePassword" style="background-color: #f8f9fc;">
                                       <i class="fas fa-key me-2 text-secondary"></i> Change Password
                                   </button>
                               </h2>
                               <div id="collapsePassword" class="accordion-collapse collapse" aria-labelledby="headingPassword" data-bs-parent="#passwordAccordion">
                                   <div class="accordion-body bg-white p-4">
                                       <p class="text-muted small mb-3">To change your password, fill in the fields below. Otherwise, leave them blank.</p>
                                       <div class="row">
                                           <div class="col-md-6 mb-3">
                                               <label for="password" class="form-label font-weight-bold">New Password</label>
                                               <input type="password" name="password" id="password" class="form-control shadow-sm" placeholder="Minimum 6 characters">
                                           </div>
                                           <div class="col-md-6 mb-3">
                                               <label for="password_confirmation" class="form-label font-weight-bold">Confirm New Password</label>
                                               <input type="password" name="password_confirmation" id="password_confirmation" class="form-control shadow-sm" placeholder="Repeat new password">
                                           </div>
                                       </div>
                                   </div>
                               </div>
                           </div>
                        </div>

                        <div class="d-flex justify-content-end gap-2">
                           <button type="reset" class="btn btn-secondary font-weight-bold px-4">Reset</button>
                           <button type="submit" class="btn btn-primary font-weight-bold px-4" style="background-color: #018ca3; border-color: #018ca3;">Save Changes</button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Danger Zone Card -->
            <div class="card border-danger shadow mb-4">
                <div class="card-header py-3 bg-danger text-white">
                    <h6 class="m-0 font-weight-bold"><i class="fas fa-exclamation-triangle me-2"></i> Danger Zone</h6>
                </div>
                <div class="card-body">
                    <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3">
                        <div>
                            <h6 class="font-weight-bold text-dark mb-1">Sign Out of Other Sessions</h6>
                            <p class="text-muted small mb-0">This will immediately log you out of all other active browser sessions on other devices. Your current session will remain active.</p>
                        </div>
                        <div>
                            <form action="{{ route('profile.logout-all') }}" method="POST" onsubmit="return confirm('Are you sure you want to sign out of all other sessions? You will need to log back in on other devices.');">
                                @csrf
                                <button type="submit" class="btn btn-danger font-weight-bold px-3">
                                    <i class="fas fa-sign-out-alt me-1"></i> Sign Out Other Devices
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Receipts warning placeholder -->
            <div class="alert alert-light border small text-muted">
                <i class="fas fa-info-circle me-1"></i> <strong>Receipts Stat Note:</strong> The "Receipts Processed" count displayed is the total receipts count in the system, as individual creator tracking is not enabled for receipts.
            </div>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const dropzone = document.getElementById('dropzone');
        const fileInput = document.getElementById('profile_picture');
        const avatarPreview = document.getElementById('avatar-preview');
        const avatarInitials = document.getElementById('avatar-initials');
        const uploadSpinner = document.getElementById('upload-spinner');
        const uploadStatus = document.getElementById('upload-status');

        // Click on dropzone to trigger file input
        dropzone.addEventListener('click', () => {
            fileInput.click();
        });

        // Drag & Drop event handlers
        ['dragenter', 'dragover'].forEach(eventName => {
            dropzone.addEventListener(eventName, (e) => {
                e.preventDefault();
                dropzone.style.background = '#f1fdfc';
                dropzone.style.borderColor = '#018ca3';
            }, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            dropzone.addEventListener(eventName, (e) => {
                e.preventDefault();
                dropzone.style.background = 'transparent';
                dropzone.style.borderColor = '#d1d3e2';
            }, false);
        });

        dropzone.addEventListener('drop', (e) => {
            const dt = e.dataTransfer;
            const files = dt.files;
            if (files.length) {
                fileInput.files = files;
                handleUpload(files[0]);
            }
        });

        // Input change handler
        fileInput.addEventListener('change', function() {
            if (fileInput.files.length) {
                handleUpload(fileInput.files[0]);
            }
        });

        // Perform Upload
        function handleUpload(file) {
            if (!file.type.match('image.*')) {
                showStatus('Please select an image file (PNG, JPG, JPEG, GIF).', 'alert-danger');
                return;
            }

            if (file.size > 2 * 1024 * 1024) {
                showStatus('File size must be less than 2MB.', 'alert-danger');
                return;
            }

            // Create preview
            const reader = new FileReader();
            reader.onload = function(e) {
                avatarPreview.src = e.target.result;
                avatarPreview.classList.remove('d-none');
                if (avatarInitials) {
                    avatarInitials.classList.add('d-none');
                }
            };
            reader.readAsDataURL(file);

            // AJAX Upload
            uploadSpinner.classList.remove('d-none');
            const formData = new FormData();
            formData.append('profile_picture', file);
            formData.append('_token', '{{ csrf_token() }}');

            fetch('{{ route("profile.photo") }}', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                uploadSpinner.classList.add('d-none');
                if (data.success) {
                    showStatus(data.message, 'alert-success');
                    // Update all navbar user images
                    document.querySelectorAll('.img-profile').forEach(img => {
                        img.src = data.url;
                        img.classList.remove('d-none');
                    });
                    // Also hide initials avatar in top nav if present
                    document.querySelectorAll('.qi-initials-avatar').forEach(span => {
                        span.classList.add('d-none');
                    });
                } else {
                    showStatus(data.message || 'Failed to upload photo.', 'alert-danger');
                }
            })
            .catch(error => {
                uploadSpinner.classList.add('d-none');
                showStatus('An error occurred during upload. Please try again.', 'alert-danger');
                console.error('Upload error:', error);
            });
        }

        function showStatus(message, className) {
            uploadStatus.textContent = message;
            uploadStatus.className = 'alert mt-2 small p-2 ' + className;
            uploadStatus.classList.remove('d-none');
            setTimeout(() => {
                uploadStatus.classList.add('d-none');
            }, 5000);
        }
    });
</script>
@endsection
