@extends('layouts.app')

@section('title', __('accounts.transfers.title'))

@push('styles')
<link href="{{ asset('css/stage-academy.css') }}" rel="stylesheet">
<link href="{{ asset('css/accounts.css') }}" rel="stylesheet">
<style>
    body.dark-mode .table {
        color: #e2e8f0;
        border-color: #334155;
    }

    body.dark-mode .table > :not(caption) > * > * {
        background-color: transparent;
        color: inherit;
        border-color: #334155;
    }

    body.dark-mode .table-hover tbody tr:hover {
        background-color: rgba(255, 255, 255, 0.05);
    }

    body.dark-mode .modal .form-text[data-available-hint] {
        color: #cbd5e1;
    }
</style>
@endpush

@section('content')
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-1">
                    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">{{ __('dashboard') }}</a></li>
                    <li class="breadcrumb-item"><a href="{{ route('accounts') }}">{{ __('accounts.title') }}</a></li>
                    <li class="breadcrumb-item active" aria-current="page">{{ __('accounts.transfers.title') }}</li>
                </ol>
            </nav>
            <h4 class="fw-bold mb-0">{{ __('accounts.transfers.title') }}</h4>
            <div class="text-muted small">{{ __('accounts.transfers.subtitle') }}</div>
        </div>
        <div class="d-flex gap-2">
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addTransferModal">
                <i class="bi bi-plus-circle me-1"></i>
                {{ __('accounts.transfers.add_button') }}
            </button>
            <a href="{{ route('accounts') }}" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-{{ app()->getLocale() == 'ar' ? 'right' : 'left' }}"></i> {{ __('common.back') }}
            </a>
        </div>
    </div>

    @if(session('success'))
        <div class="alert alert-success">{{ session('success') }}</div>
    @endif

    @if($errors->any())
        <div class="alert alert-danger">
            <div class="fw-semibold mb-1">{{ __('accounts.transfers.validation.title') }}</div>
            <ul class="mb-0 ps-3">
                @foreach($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <div class="card sa-card mb-3">
        <div class="card-body">
            <form action="{{ route('accounts.transfers') }}" method="GET" class="row g-2 align-items-end">
                <div class="col-6 col-lg-3">
                    <label class="form-label mb-1">{{ __('accounts.transfers.filter_from') }}</label>
                    <input type="date" class="form-control shadow-sm" name="from_date" value="{{ request('from_date') }}">
                </div>
                <div class="col-6 col-lg-3">
                    <label class="form-label mb-1">{{ __('accounts.transfers.filter_to') }}</label>
                    <input type="date" class="form-control shadow-sm" name="to_date" value="{{ request('to_date') }}">
                </div>
                <div class="col-12 col-lg-2 d-grid">
                    <button class="btn btn-primary shadow-sm" type="submit">{{ __('accounts.transfers.apply') }}</button>
                </div>
                <div class="col-12 col-lg-4 text-muted small">
                    {{ __('accounts.transfers.note') }}
                </div>
            </form>
        </div>
    </div>

    <div class="card shadow-sm border-0">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="bg-light">
                        <tr>
                            <th class="py-3 ps-4">{{ __('accounts.transfers.amount') }}</th>
                            <th class="py-3">{{ __('accounts.transfers.from') }}</th>
                            <th class="py-3">{{ __('accounts.transfers.to') }}</th>
                            <th class="py-3">{{ __('accounts.transfers.date') }}</th>
                            <th class="py-3">{{ __('accounts.transfers.created_by') }}</th>
                            <th class="py-3 text-end pe-4">{{ __('accounts.transfers.actions') }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($transfers as $transfer)
                            <tr>
                                <td class="ps-4 fw-semibold">{{ number_format((int) $transfer->amount, 0) }}</td>
                                <td>{{ $boxes[$transfer->from_box] ?? $transfer->from_box }}</td>
                                <td>{{ $boxes[$transfer->to_box] ?? $transfer->to_box }}</td>
                                <td>{{ \Carbon\Carbon::parse($transfer->transfer_date)->format('Y-m-d') }}</td>
                                <td class="text-muted">{{ $transfer->creator?->name ?: '-' }}</td>
                                <td class="text-end pe-4">
                                    <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#editTransferModal{{ $transfer->id }}" title="{{ __('common.edit') }}">
                                        <i class="bi bi-pencil"></i>
                                    </button>
                                    <form action="{{ route('accounts.transfers.destroy', $transfer->id) }}" method="POST" class="d-inline">
                                        @csrf
                                        @method('DELETE')
                                        <button type="submit" class="btn btn-sm btn-outline-danger" title="{{ __('common.delete') }}">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>

                            @php
                                $editBalances = $boxBalances ?? [];
                                if (isset($editBalances[$transfer->from_box])) {
                                    $editBalances[$transfer->from_box] = (int) $editBalances[$transfer->from_box] + (int) $transfer->amount;
                                }
                                if (isset($editBalances[$transfer->to_box])) {
                                    $editBalances[$transfer->to_box] = (int) $editBalances[$transfer->to_box] - (int) $transfer->amount;
                                }
                            @endphp
                            <div class="modal fade" id="editTransferModal{{ $transfer->id }}" tabindex="-1" aria-hidden="true" data-transfer-balances="{{ json_encode($editBalances) }}">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title">{{ __('accounts.transfers.edit_title') }}</h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                        </div>
                                        <form action="{{ route('accounts.transfers.update', $transfer->id) }}" method="POST">
                                            @csrf
                                            @method('PUT')
                                            <div class="modal-body">
                                                <div class="mb-3">
                                                    <label class="form-label">{{ __('accounts.transfers.amount') }}</label>
                                                    <input type="number" min="1" step="1" class="form-control" name="amount" value="{{ session('edit_transfer_id') == $transfer->id ? old('amount', (int) $transfer->amount) : (int) $transfer->amount }}" required>
                                                </div>
                                                <div class="mb-3">
                                                    <div class="form-label">{{ __('accounts.transfers.box') }}</div>
                                                    <div class="row g-2">
                                                        <div class="col-6">
                                                            <label class="form-label small">{{ __('accounts.transfers.from') }}</label>
                                                            <select class="form-select" name="from_box" required>
                                                                @foreach($boxes as $key => $label)
                                                                    <option value="{{ $key }}" @selected((session('edit_transfer_id') == $transfer->id ? old('from_box', $transfer->from_box) : $transfer->from_box) === $key)>{{ $label }}</option>
                                                                @endforeach
                                                            </select>
                                                            <div class="form-text d-none" data-available-hint="from"></div>
                                                        </div>
                                                        <div class="col-6">
                                                            <label class="form-label small">{{ __('accounts.transfers.to') }}</label>
                                                            <select class="form-select" name="to_box" required>
                                                                @foreach($boxes as $key => $label)
                                                                    <option value="{{ $key }}" @selected((session('edit_transfer_id') == $transfer->id ? old('to_box', $transfer->to_box) : $transfer->to_box) === $key)>{{ $label }}</option>
                                                                @endforeach
                                                            </select>
                                                            <div class="form-text d-none" data-available-hint="to"></div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="mb-0">
                                                    <label class="form-label">{{ __('accounts.transfers.date') }}</label>
                                                    <input type="date" class="form-control" name="transfer_date" value="{{ session('edit_transfer_id') == $transfer->id ? old('transfer_date', \Carbon\Carbon::parse($transfer->transfer_date)->format('Y-m-d')) : \Carbon\Carbon::parse($transfer->transfer_date)->format('Y-m-d') }}" required>
                                                </div>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">{{ __('common.cancel') }}</button>
                                                <button type="submit" class="btn btn-primary">{{ __('common.save') }}</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        @empty
                            <tr>
                                <td colspan="6" class="text-center py-5 text-muted">
                                    <i class="bi bi-arrow-left-right fs-1 mb-3 d-block"></i>
                                    {{ __('accounts.transfers.empty') }}
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
        @if($transfers->hasPages())
            <div class="card-footer bg-white border-top-0 py-3">
                {{ $transfers->links() }}
            </div>
        @endif
    </div>
</div>

<div class="modal fade" id="addTransferModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">{{ __('accounts.transfers.add_title') }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="{{ route('accounts.transfers.store') }}" method="POST">
                @csrf
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">{{ __('accounts.transfers.amount') }}</label>
                        <input type="number" min="1" step="1" class="form-control" name="amount" value="{{ old('amount') }}" required>
                    </div>
                    <div class="mb-3">
                        <div class="form-label">{{ __('accounts.transfers.box') }}</div>
                        <div class="row g-2">
                            <div class="col-6">
                                <label class="form-label small">{{ __('accounts.transfers.from') }}</label>
                                <select class="form-select" name="from_box" required>
                                    <option value="">{{ __('common.select') }}</option>
                                    @foreach($boxes as $key => $label)
                                        <option value="{{ $key }}" @selected(old('from_box') === $key)>{{ $label }}</option>
                                    @endforeach
                                </select>
                                <div class="form-text d-none" data-available-hint="from"></div>
                            </div>
                            <div class="col-6">
                                <label class="form-label small">{{ __('accounts.transfers.to') }}</label>
                                <select class="form-select" name="to_box" required>
                                    <option value="">{{ __('common.select') }}</option>
                                    @foreach($boxes as $key => $label)
                                        <option value="{{ $key }}" @selected(old('to_box') === $key)>{{ $label }}</option>
                                    @endforeach
                                </select>
                                <div class="form-text d-none" data-available-hint="to"></div>
                            </div>
                        </div>
                    </div>
                    <div class="mb-0">
                        <label class="form-label">{{ __('accounts.transfers.date') }}</label>
                        <input type="date" class="form-control" name="transfer_date" value="{{ old('transfer_date', now()->format('Y-m-d')) }}" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">{{ __('common.cancel') }}</button>
                    <button type="submit" class="btn btn-primary">{{ __('common.save') }}</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div id="transfersBalancesData" class="d-none"
    data-box-balances="{{ json_encode($boxBalances ?? []) }}"
    data-available-now-label="{{ __('accounts.transfers.available_now') }}"
    data-locale="{{ app()->getLocale() }}"
    data-open-add="{{ session('open_transfer_add_modal') ? '1' : '0' }}"
    data-edit-id="{{ session('edit_transfer_id') }}">
</div>

<script>
    function formatInt(value) {
        const configEl = document.getElementById('transfersBalancesData');
        const locale = (configEl && configEl.getAttribute('data-locale')) ? configEl.getAttribute('data-locale') : 'en';
        const number = Number(value || 0);
        return new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(number);
    }

    function initModalBalanceHints(modalEl, balances) {
        const fromSelect = modalEl.querySelector('select[name="from_box"]');
        const toSelect = modalEl.querySelector('select[name="to_box"]');
        const fromHint = modalEl.querySelector('[data-available-hint="from"]');
        const toHint = modalEl.querySelector('[data-available-hint="to"]');

        function updateHint(selectEl, hintEl) {
            if (!selectEl || !hintEl) return;
            const key = selectEl.value;
            if (!key) {
                hintEl.classList.add('d-none');
                hintEl.textContent = '';
                return;
            }
            const available = Number((balances && balances[key] != null) ? balances[key] : 0);
            const configEl = document.getElementById('transfersBalancesData');
            const label = (configEl && configEl.getAttribute('data-available-now-label')) ? configEl.getAttribute('data-available-now-label') : 'Available now';
            hintEl.textContent = label + ': ' + formatInt(available);
            hintEl.classList.remove('d-none');
        }

        if (fromSelect) {
            fromSelect.addEventListener('change', function () {
                updateHint(fromSelect, fromHint);
            });
        }

        if (toSelect) {
            toSelect.addEventListener('change', function () {
                updateHint(toSelect, toHint);
            });
        }

        updateHint(fromSelect, fromHint);
        updateHint(toSelect, toHint);
    }

    document.addEventListener('DOMContentLoaded', function () {
        const configEl = document.getElementById('transfersBalancesData');
        const baseBalances = configEl ? JSON.parse(configEl.getAttribute('data-box-balances') || '{}') : {};

        const addModal = document.getElementById('addTransferModal');
        if (addModal) {
            initModalBalanceHints(addModal, baseBalances);
        }

        document.querySelectorAll('[data-transfer-balances]').forEach(function (modalEl) {
            try {
                const balances = JSON.parse(modalEl.getAttribute('data-transfer-balances') || '{}');
                initModalBalanceHints(modalEl, balances);
            } catch (e) {
                initModalBalanceHints(modalEl, baseBalances);
            }
        });

        const openAdd = configEl ? (configEl.getAttribute('data-open-add') === '1') : false;
        if (openAdd && addModal && window.bootstrap && bootstrap.Modal) {
            bootstrap.Modal.getOrCreateInstance(addModal).show();
        }

        const editId = configEl ? (configEl.getAttribute('data-edit-id') || '') : '';
        if (editId) {
            const editModal = document.getElementById('editTransferModal' + editId);
            if (editModal && window.bootstrap && bootstrap.Modal) {
                bootstrap.Modal.getOrCreateInstance(editModal).show();
            }
        }
    });
</script>
@endsection
