@extends('layouts.app')

@section('title', 'Edit Application')

@section('content')
<div class="row mb-5">
    <div class="col-12 d-flex justify-content-between align-items-end">
        <div>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-2">
                    <li class="breadcrumb-item"><a href="{{ route('admin.dashboard') }}"
                            class="text-decoration-none">Dashboard</a></li>
                    <li class="breadcrumb-item"><a href="{{ route('admin.applications.index') }}"
                            class="text-decoration-none">Applications</a></li>
                    <li class="breadcrumb-item active">Edit</li>
                </ol>
            </nav>
            <h2 class="fw-bold mb-0">Update Details</h2>
        </div>
        <a href="{{ route('admin.applications.index') }}" class="btn btn-outline-primary rounded-pill px-4">
            <i class="bi bi-chevron-left me-1"></i> Back to Inventory
        </a>
    </div>
</div>

<div class="alert alert-secondary glass-card border-0 rounded-4 mb-4 py-3">
    <div class="d-flex flex-wrap gap-4 align-items-center px-2">
        <div class="d-flex align-items-center">
            <i class="bi bi-hdd-fill text-primary me-2"></i>
            <div><small class="text-muted d-block">Combined
                    Size</small><strong>{{ $app_model->download_size_human ?? 'Unknown' }}</strong></div>
        </div>
        <div class="d-flex align-items-center">
            <i class="bi bi-link-45deg text-primary me-2"></i>
            <div><small class="text-muted d-block">Legacy
                    Path</small><code>{{ $app_model->download_url ?? 'None' }}</code></div>
        </div>
    </div>
</div>

<div class="glass-card p-4 p-lg-5 rounded-4 border-0 shadow-sm">
    <form id="uploadForm" method="POST" action="{{ rtrim(request()->getBaseUrl(), '/') }}/admin/applications/{{ $app_model->id }}"
        enctype="multipart/form-data">
        @csrf
        <div class="row g-4">
            <div class="col-md-6">
                <label class="form-label small fw-600">Application Name</label>
                <input type="text" name="name" class="form-control bg-light-custom border-0 py-2"
                    value="{{ old('name', $app_model->name) }}" required>
            </div>
            <div class="col-md-3">
                <label class="form-label small fw-600">Platform</label>
                <select name="platform" id="platformSelect" class="form-select bg-light-custom border-0 py-2" required>
                    @foreach(['Android','PC','iOS','macOS'] as $platform)
                    <option value="{{ $platform }}" {{ $app_model->platform === $platform ? 'selected' : '' }}>
                        {{ $platform }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label small fw-600">Version</label>
                <input type="text" name="version" class="form-control bg-light-custom border-0 py-2"
                    value="{{ old('version', $app_model->version) }}" required>
            </div>

            <div class="col-md-6">
                <label class="form-label small fw-600">Category</label>
                <select name="category_id" class="form-select bg-light-custom border-0 py-2" required>
                    @foreach($categories as $category)
                    <option value="{{ $category->id }}"
                        {{ $app_model->category_id === $category->id ? 'selected' : '' }}>{{ $category->name }}</option>
                    @endforeach
                </select>
            </div>

            <div class="col-md-6">
                <label class="form-label small fw-600">Replace Icon</label>
                <input type="file" name="icon" class="form-control bg-light-custom border-0 py-2 mb-2">
                @if($app_model->icon_path)
                <div class="d-flex align-items-center gap-2 mt-2">
                    <img src="{{ asset('storage/' . ltrim($app_model->icon_path, '/')) }}"
                        class="rounded shadow-sm border" width="48" height="48" alt="">
                    <small class="text-muted">Current icon being served</small>
                </div>
                @endif
            </div>

            <div class="col-12">
                <label class="form-label small fw-600">Application Description</label>
                <textarea name="description" rows="4" class="form-control bg-light-custom border-0 py-2"
                    required>{{ old('description', $app_model->description) }}</textarea>
            </div>

            <div class="col-12">
                <div class="p-4 bg-light-custom rounded-4 border-dashed">
                    <label class="form-label d-flex justify-content-between align-items-center mb-3">
                        <span class="fw-bold" id="archTitle">Application Files</span>
                        <button type="button" id="addArch" class="btn btn-sm btn-primary rounded-pill px-3 shadow-sm">+
                            Add Architecture</button>
                    </label>
                    <div id="archContainer">
                        @foreach($app_model->files as $index => $file)
                        <div class="card bg-card-inner border-0 mb-3 arch-row p-3 shadow-sm transition">
                            <input type="hidden" name="arch_files[{{ $index }}][id]" value="{{ $file->id }}">
                            <div class="row g-3 align-items-end">
                                <div class="col-md-3 arch-col">
                                    <label class="small text-muted fw-600 mb-1">Architecture</label>
                                    <select name="arch_files[{{ $index }}][architecture]"
                                        class="form-select border-0 bg-light-custom" required>
                                        @foreach(['Universal', 'arm64-v8a', 'armeabi-v7a', 'x86', 'x86_64'] as $arch)
                                        <option value="{{ $arch }}"
                                            {{ $file->architecture == $arch ? 'selected' : '' }}>{{ $arch }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-md-5 file-col">
                                    <label class="small text-muted fw-600 mb-1">Replace File (Optional)</label>
                                    <input type="file" name="arch_files[{{ $index }}][file]"
                                        class="form-control border-0 bg-light-custom">
                                    <small class="text-truncate d-block mt-1 opacity-75"><i
                                            class="bi bi-file-earmark-check me-1"></i>{{ basename($file->file_path) }}</small>
                                </div>
                                <div class="col-md-3 stat-col text-center">
                                    <span
                                        class="badge bg-secondary-subtle text-secondary px-3 py-2 rounded-pill">{{ $file->file_size_human }}</span>
                                </div>
                                <div class="col-md-1 remove-col text-end">
                                    <button type="button" class="btn btn-outline-danger border-0 remove-arch"><i
                                            class="bi bi-trash3"></i></button>
                                </div>
                            </div>
                        </div>
                        @endforeach

                        @if($app_model->files->isEmpty())
                        <div class="card bg-card-inner border-0 mb-3 arch-row p-3 shadow-sm transition">
                            <div class="row g-3 align-items-end">
                                <div class="col-md-4 arch-col">
                                    <label class="small text-muted fw-600 mb-1">Target Architecture</label>
                                    <select name="arch_files[0][architecture]"
                                        class="form-select border-0 bg-light-custom" required>
                                        <option value="Universal">Universal / All</option>
                                        <option value="arm64-v8a">arm64-v8a</option>
                                        <option value="armeabi-v7a">armeabi-v7a</option>
                                        <option value="x86">x86</option>
                                        <option value="x86_64">x86_64</option>
                                    </select>
                                </div>
                                <div class="col-md-7 file-col">
                                    <label class="small text-muted fw-600 mb-1">Upload File</label>
                                    <input type="file" name="arch_files[0][file]"
                                        class="form-control border-0 bg-light-custom">
                                </div>
                                <div class="col-md-1 remove-col text-end">
                                    <button type="button" class="btn btn-outline-danger border-0 remove-arch"
                                        disabled><i class="bi bi-trash3"></i></button>
                                </div>
                            </div>
                        </div>
                        @endif
                    </div>
                </div>
            </div>

            <div class="col-12">
                <div id="uploadError" class="alert alert-danger d-none animate-fade-in" role="alert"></div>
                <div id="uploadProgress" class="d-none animate-fade-in">
                    <div class="d-flex justify-content-between align-items-end mb-2">
                        <label class="form-label small fw-bold mb-0">Upload Progress</label>
                        <span id="uploadPercent" class="small fw-bold text-primary">0%</span>
                    </div>
                    <div class="progress" style="height: 10px; border-radius: 10px;">
                        <div id="uploadProgressBar" class="progress-bar progress-bar-striped progress-bar-animated"
                            role="progressbar" style="width: 0%;"></div>
                    </div>
                    <div id="uploadProgressStatus" class="small text-muted mt-2 fw-600">Preparing files...</div>
                </div>
            </div>

            <div class="col-12 text-end mt-4">
                <button type="submit" class="btn btn-primary px-5 py-3 rounded-pill shadow-lg fw-bold">
                    <i class="bi bi-check2-circle me-2"></i> Save Changes
                </button>
            </div>
        </div>
    </form>
</div>

<style>
.bg-light-custom {
    background-color: rgba(0, 0, 0, 0.03);
}

.bg-card-inner {
    background-color: var(--bg-card);
}

.border-dashed {
    border: 2px dashed rgba(0, 0, 0, 0.1);
}

.transition {
    transition: all 0.3s ease;
}

[data-theme="dark"] .bg-light-custom {
    background-color: rgba(255, 255, 255, 0.05);
}

[data-theme="dark"] .border-dashed {
    border-color: rgba(255, 255, 255, 0.1);
}

[data-theme="dark"] .form-control,
[data-theme="dark"] .form-select {
    color: var(--text-main);
}

[data-theme="dark"] .form-control::placeholder {
    color: rgba(255, 255, 255, 0.3);
}

[data-theme="dark"] .bg-secondary-subtle {
    background-color: rgba(255, 255, 255, 0.1) !important;
    color: #f8fafc !important;
}

.animate-fade-in {
    animation: fadeIn 0.4s ease-out;
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const archContainer = document.getElementById('archContainer');
    const addArchBtn = document.getElementById('addArch');
    const platformSelect = document.getElementById('platformSelect');
    const archHeaderLabel = document.getElementById('archTitle');
    let archCount = {{ max(1, $app_model->files->count()) }};

    function toggleArchView() {
        const isAndroid = platformSelect.value === 'Android';

        if (isAndroid) {
            addArchBtn.classList.remove('d-none');
            archHeaderLabel.textContent = 'Application Files (Multi-Architecture)';
        } else {
            addArchBtn.classList.add('d-none');
            archHeaderLabel.textContent = 'Application File';
            while (document.querySelectorAll('.arch-row').length > 1) {
                document.querySelectorAll('.arch-row')[document.querySelectorAll('.arch-row').length - 1]
                    .remove();
            }
        }

        document.querySelectorAll('.arch-row').forEach(row => {
            const archCol = row.querySelector('.arch-col');
            const fileCol = row.querySelector('.file-col');
            const statCol = row.querySelector('.stat-col');
            const removeCol = row.querySelector('.remove-col');

            if (isAndroid) {
                archCol.classList.remove('d-none');
                if (statCol) statCol.classList.remove('d-none');
                fileCol.className = (statCol ? 'col-md-5' : 'col-md-7') + ' file-col';
                removeCol.classList.remove('d-none');
            } else {
                archCol.classList.add('d-none');
                if (statCol) statCol.classList.add('d-none');
                fileCol.className = 'col-md-12 file-col';
                removeCol.classList.add('d-none');
                row.querySelector('select').value = 'Universal';
            }
        });
    }

    platformSelect.addEventListener('change', toggleArchView);

    addArchBtn.addEventListener('click', function() {
        const newRow = document.createElement('div');
        newRow.className = 'card bg-card-inner border-0 mb-3 arch-row p-3 shadow-sm transition';
        newRow.innerHTML = `
                <div class="row g-3 align-items-end">
                    <div class="col-md-4 arch-col">
                        <label class="small text-muted fw-600 mb-1">Architecture</label>
                        <select name="arch_files[${archCount}][architecture]" class="form-select border-0 bg-light-custom" required>
                            <option value="Universal">Universal / All</option>
                            <option value="arm64-v8a">arm64-v8a</option>
                            <option value="armeabi-v7a">armeabi-v7a</option>
                            <option value="x86">x86</option>
                            <option value="x86_64">x86_64</option>
                        </select>
                    </div>
                    <div class="col-md-7 file-col">
                        <label class="small text-muted fw-600 mb-1">Upload File</label>
                        <input type="file" name="arch_files[${archCount}][file]" class="form-control border-0 bg-light-custom" required>
                    </div>
                    <div class="col-md-1 remove-col text-end">
                        <button type="button" class="btn btn-outline-danger border-0 remove-arch"><i class="bi bi-trash3"></i></button>
                    </div>
                </div>
            `;
        archContainer.appendChild(newRow);
        archCount++;
        updateRemoveButtons();
        toggleArchView();
    });

    archContainer.addEventListener('click', function(e) {
        if (e.target.closest('.remove-arch')) {
            e.target.closest('.arch-row').remove();
            updateRemoveButtons();
        }
    });

    function updateRemoveButtons() {
        const btns = document.querySelectorAll('.remove-arch');
        btns.forEach((btn) => {
            btn.disabled = btns.length === 1;
        });
    }

    const form = document.getElementById('uploadForm');
    const progressBox = document.getElementById('uploadProgress');
    const progressBar = document.getElementById('uploadProgressBar');
    const percentText = document.getElementById('uploadPercent');
    const progressStatus = document.getElementById('uploadProgressStatus');
    const errorBox = document.getElementById('uploadError');
    const submitButton = form.querySelector('button[type="submit"]');
    const chunkUrl = @json(rtrim(request()->getSchemeAndHttpHost() . request()->getBaseUrl(), '/') . '/admin/upload-chunk');
    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    // Server validates each chunk at max 2560 KB (AdminController::uploadChunk); stay under that.
    const CHUNK_SIZE = 2 * 1024 * 1024; // 2 MiB — halves round-trips vs 1 MiB for large APKs
    const DIRECT_UPLOAD_MAX = 2 * 1024 * 1024; // skip chunking for small files

    console.log('Chunk upload init:', chunkUrl);

    function makeUploadId() {
        return 'upload_' + Date.now() + '_' + Math.random().toString(36).substring(2, 12);
    }

    function updateProgress(uploadedBytes, totalBytes) {
        const percent = totalBytes > 0 ? Math.round((uploadedBytes / totalBytes) * 100) : 0;
        progressBar.style.width = percent + '%';
        percentText.textContent = percent + '%';
    }

    function showError(message) {
        submitButton.disabled = false;
        errorBox.textContent = message;
        errorBox.classList.remove('d-none');
        progressStatus.textContent = 'Upload failed.';
        progressBar.classList.add('bg-danger');
    }

    async function sendChunkRequest(formData) {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.open('POST', chunkUrl);
            xhr.withCredentials = true;
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.setRequestHeader('Accept', 'application/json');
            xhr.setRequestHeader('X-CSRF-TOKEN', csrfToken);

            xhr.onload = function() {
                if (xhr.status >= 200 && xhr.status < 300) {
                    try {
                        resolve(JSON.parse(xhr.responseText));
                    } catch (error) {
                        reject(new Error('Invalid server response.'));
                    }
                } else {
                    reject(new Error(xhr.responseText || 'Chunk upload failed.'));
                }
            };

            xhr.onerror = function() {
                reject(new Error('Chunk upload failed (connection reset). Try a smaller file or ask your host to raise upload_max_filesize / post_max_size.'));
            };

            xhr.send(formData);
        });
    }

    async function uploadFileChunks(file, index, progressCallback) {
        const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
        const uploadId = makeUploadId();
        let uploadedBytes = 0;
        let tempPath = null;

        for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
            const start = chunkIndex * CHUNK_SIZE;
            const end = Math.min(start + CHUNK_SIZE, file.size);
            const chunk = file.slice(start, end);
            const chunkForm = new FormData();
            chunkForm.append('_token', csrfToken);
            chunkForm.append('upload_id', uploadId);
            chunkForm.append('file_index', index);
            chunkForm.append('chunk_index', chunkIndex);
            chunkForm.append('chunk_count', totalChunks);
            chunkForm.append('file_name', file.name);
            chunkForm.append('file_size', file.size);
            chunkForm.append('chunk', chunk, file.name);

            progressStatus.textContent = `Uploading ${file.name} (${chunkIndex + 1}/${totalChunks})...`;
            const response = await sendChunkRequest(chunkForm);
            tempPath = response.temp_path;
            uploadedBytes += chunk.size;
            progressCallback(chunk.size, uploadedBytes);
        }

        return tempPath;
    }

    function buildFinalForm(form, tempPaths) {
        const finalForm = new FormData();
        const sourceForm = new FormData(form);

        sourceForm.forEach((value, key) => {
            const archFileMatch = key.match(/^arch_files\[(\d+)\]\[file\]$/);
            if (archFileMatch) {
                const idx = parseInt(archFileMatch[1], 10);
                if (tempPaths[idx]) {
                    return;
                }
            }
            finalForm.append(key, value);
        });

        tempPaths.forEach((tempPath, index) => {
            if (tempPath) {
                finalForm.append(`arch_files[${index}][temp_path]`, tempPath);
            }
        });

        return finalForm;
    }

    function submitFinalForm(finalForm) {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.open('POST', form.action);
            xhr.withCredentials = true;
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.setRequestHeader('Accept', 'application/json');
            xhr.setRequestHeader('X-CSRF-TOKEN', csrfToken);

            xhr.onload = function() {
                submitButton.disabled = false;
                if (xhr.status >= 200 && xhr.status < 300) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        if (response.redirect) {
                            window.location = response.redirect;
                            return;
                        }
                        resolve(response);
                    } catch (error) {
                        resolve({});
                    }
                } else {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        reject(new Error(response.message || Object.values(response.errors || {})
                            .flat().join(' ') || 'Upload failed.'));
                    } catch (error) {
                        reject(new Error('Upload failed.'));
                    }
                }
            };

            xhr.onerror = function() {
                submitButton.disabled = false;
                reject(new Error('Network error while submitting the form.'));
            };

            xhr.send(finalForm);
        });
    }

    form.addEventListener('submit', async function(event) {
        console.log('Intercepted upload submit', form.action);
        event.preventDefault();
        errorBox.classList.add('d-none');
        errorBox.textContent = '';
        submitButton.disabled = true;
        progressBox.classList.remove('d-none');
        progressBar.classList.remove('bg-danger');
        progressBar.style.width = '0%';
        percentText.textContent = '0%';
        progressStatus.textContent = 'Preparing upload...';

        const archRows = Array.from(archContainer.querySelectorAll('.arch-row'));
        const iconInput = form.querySelector('input[type="file"][name="icon"]');
        const iconBytes = iconInput?.files?.[0]?.size || 0;
        const archBytes = archRows.reduce((total, row) => {
            const fileInput = row.querySelector('input[type="file"]');
            return total + (fileInput?.files?.[0]?.size || 0);
        }, 0);
        const totalBytes = archBytes + iconBytes;

        try {
            if (totalBytes === 0) {
                progressStatus.textContent = 'Saving changes...';
                await submitFinalForm(new FormData(form));
                return;
            }

            // Icon max 2048 KiB server-side — always stays on direct multipart path with arch files ≤ 2 MiB.
            if (totalBytes <= DIRECT_UPLOAD_MAX) {
                progressStatus.textContent = 'Uploading...';
                updateProgress(0, totalBytes);
                await submitFinalForm(new FormData(form));
                return;
            }

            let uploadedBytes = 0;
            const tempPaths = [];

            // Chunk-upload each large arch APK only (icon remains on final multipart request).
            for (let index = 0; index < archRows.length; index++) {
                const row = archRows[index];
                const fileInput = row.querySelector('input[type="file"]');
                const file = fileInput?.files?.[0];

                if (!file) {
                    continue;
                }

                if (file.size <= DIRECT_UPLOAD_MAX) {
                    uploadedBytes += file.size;
                    updateProgress(uploadedBytes, totalBytes);
                    continue;
                }

                const tempPath = await uploadFileChunks(file, index, (chunkSize) => {
                    uploadedBytes += chunkSize;
                    updateProgress(uploadedBytes, totalBytes);
                });
                tempPaths[index] = tempPath;
            }

            progressStatus.textContent = 'Finishing upload...';
            updateProgress(totalBytes, totalBytes);
            const finalForm = buildFinalForm(form, tempPaths);
            await submitFinalForm(finalForm);
        } catch (error) {
            showError(error.message || 'An unexpected upload error occurred.');
        }
    });

    updateRemoveButtons();
    toggleArchView();
});
</script>
@endsection