@extends('layouts.app')
@section('title', 'Currencies')

@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item active">Currencies</li>
@endsection

@section('content')
<div class="page-header">
    <div>
        <h1 class="page-title">Currencies</h1>
        <p class="page-subtitle">Manage currencies and exchange rates</p>
    </div>
</div>

<div class="row g-4">
    {{-- Currency List --}}
    <div class="col-12 col-xl-7">

        {{-- Base Currency Info --}}
        @php $base = $currencies->firstWhere('is_base', true); @endphp
        @if($base)
        <div class="alert alert-success d-flex align-items-center gap-2 mb-3" style="font-size:13.5px">
            <i class="bi bi-star-fill text-warning"></i>
            <div><strong>Base Currency:</strong> {{ $base->code }} ({{ $base->name }}) — {{ $base->symbol }}</div>
        </div>
        @endif

        <div class="card mb-4">
            <div class="card-header fw-semibold">
                <i class="bi bi-currency-exchange me-2 text-primary"></i>All Currencies
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Code</th>
                                <th>Name</th>
                                <th class="d-none d-sm-table-cell">Symbol</th>
                                <th class="d-none d-md-table-cell text-center">Dec.</th>
                                <th>Type</th>
                                <th>Status</th>
                                <th style="width:92px">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($currencies as $currency)
                            <tr>
                                <td><code class="fw-semibold" style="font-size:13px">{{ $currency->code }}</code></td>
                                <td style="font-size:13.5px">{{ $currency->name }}</td>
                                <td class="d-none d-sm-table-cell"><strong>{{ $currency->symbol }}</strong></td>
                                <td class="d-none d-md-table-cell text-center text-muted" style="font-size:13px">{{ $currency->decimal_places }}</td>
                                <td>
                                    @if($currency->is_base)
                                        <span class="badge" style="background:#d1e7dd;color:#0a3622;font-size:11px">Base</span>
                                    @else
                                        <span class="badge bg-light text-dark border" style="font-size:11px">Foreign</span>
                                    @endif
                                </td>
                                <td>
                                    <span class="badge" style="background:{{ $currency->is_active ? '#d1e7dd':'#f8d7da' }};color:{{ $currency->is_active ? '#0a3622':'#842029' }};font-size:11px">
                                        {{ $currency->is_active ? 'Active' : 'Inactive' }}
                                    </span>
                                </td>
                                <td>
                                    @if(!$currency->is_base && auth()->user()->hasPermission('settings','edit'))
                                    <div class="d-flex gap-1">
                                        <button class="btn btn-outline-primary btn-sm btn-edit-cur"
                                            data-url="{{ route('masters.currencies.update', $currency) }}"
                                            data-name="{{ $currency->name }}" data-symbol="{{ $currency->symbol }}"
                                            data-decimals="{{ $currency->decimal_places }}"
                                            data-active="{{ $currency->is_active ? '1':'0' }}"
                                            title="Edit">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <form method="POST" action="{{ route('masters.currencies.destroy', $currency) }}" onsubmit="return confirm('Delete {{ addslashes($currency->code) }} permanently? This is allowed only if the currency has never been used. Used currencies should be inactive instead.')">
                                            @csrf @method('DELETE')
                                            <button type="submit" class="btn btn-outline-danger btn-sm" title="Delete permanently">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                    @endif
                                </td>
                            </tr>
                            @empty
                            <tr><td colspan="7" class="text-center py-4 text-muted">No currencies added yet.</td></tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        {{-- Exchange Rates (N+1 fixed — rates pre-loaded from controller) --}}
        @foreach($currencies->where('is_base', false) as $currency)
        @php $rates = $allRates->get($currency->id, collect())->take(5); @endphp
        <div class="card mb-3">
            <div class="card-header fw-semibold d-flex align-items-center justify-content-between">
                <span>
                    <i class="bi bi-graph-up me-2 text-primary"></i>
                    {{ $currency->code }} — Exchange Rates
                </span>
                <span class="badge bg-light text-dark border">{{ $currency->symbol }}</span>
            </div>
            <div class="card-body">
                @if(auth()->user()->hasPermission('settings','edit'))
                <form method="POST" action="{{ route('masters.currencies.rate', $currency) }}" class="mb-3">
                @csrf @method('PUT')
                <div class="row g-2 align-items-end">
                    <div class="col-12 col-sm-4">
                        <label class="form-label mb-1 fw-semibold" style="font-size:12px">Date</label>
                        <input type="date" name="rate_date" class="form-control form-control-sm"
                               value="{{ date('Y-m-d') }}" required>
                    </div>
                    <div class="col-12 col-sm-5">
                        <label class="form-label mb-1 fw-semibold" style="font-size:12px">
                            Rate <span class="text-muted fw-normal">(1 base = X {{ $currency->code }})</span>
                        </label>
                        <input type="number" name="rate" class="form-control form-control-sm"
                               value="{{ $rates->first()?->rate ?? '1' }}"
                               step="0.000001" min="0.000001" required>
                    </div>
                    <div class="col-12 col-sm-3">
                        <button type="submit" class="btn btn-primary btn-sm w-100">
                            <i class="bi bi-check-lg me-1"></i>Set Rate
                        </button>
                    </div>
                </div>
                </form>
                @endif
                @if($rates->count() > 0)
                <table class="table table-sm table-borderless mb-0" style="font-size:12.5px">
                    <thead><tr class="text-muted border-bottom"><th>Date</th><th class="text-end">Rate</th></tr></thead>
                    <tbody>
                        @foreach($rates as $rate)
                        <tr>
                            <td>{{ $rate->rate_date->format('d M Y') }}</td>
                            <td class="text-end fw-semibold">{{ number_format($rate->rate, 6) }}</td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
                @else
                <p class="text-muted mb-0" style="font-size:13px">No rates set yet. Add the first rate above.</p>
                @endif
            </div>
        </div>
        @endforeach
    </div>

    {{-- Add Currency + Reference --}}
    <div class="col-12 col-xl-5">
        @if(auth()->user()->hasPermission('settings','edit'))
        <div class="card mb-4">
            <div class="card-header fw-semibold">
                <i class="bi bi-plus-circle me-2 text-primary"></i>Add Currency
            </div>
            <div class="card-body">
                <form method="POST" action="{{ route('masters.currencies.store') }}">
                @csrf
                <div class="row g-3">
                    <div class="col-4">
                        <label class="form-label fw-semibold">Code <span class="text-danger">*</span></label>
                        <input type="text" name="code"
                               class="form-control @error('code') is-invalid @enderror"
                               value="{{ old('code') }}" placeholder="USD" maxlength="3" required
                               style="text-transform:uppercase;letter-spacing:2px;font-weight:600">
                        @error('code')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>
                    <div class="col-4">
                        <label class="form-label fw-semibold">Symbol <span class="text-danger">*</span></label>
                        <input type="text" name="symbol"
                               class="form-control @error('symbol') is-invalid @enderror"
                               value="{{ old('symbol') }}" placeholder="$" maxlength="10" required
                               style="font-size:16px;text-align:center;font-weight:600">
                        @error('symbol')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>
                    <div class="col-4">
                        <label class="form-label fw-semibold">Decimals</label>
                        <select name="decimal_places" class="form-select">
                            @foreach([0,1,2,3,4] as $d)
                                <option value="{{ $d }}" {{ old('decimal_places',2)==$d ? 'selected':'' }}>{{ $d }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-12">
                        <label class="form-label fw-semibold">Currency Name <span class="text-danger">*</span></label>
                        <input type="text" name="name"
                               class="form-control @error('name') is-invalid @enderror"
                               value="{{ old('name') }}" placeholder="e.g. US Dollar" required>
                        @error('name')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>
                    <div class="col-12">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="bi bi-plus-circle me-1"></i>Add Currency
                        </button>
                    </div>
                </div>
                </form>
            </div>
        </div>
        @endif

        <div class="card">
            <div class="card-header fw-semibold">
                <i class="bi bi-globe me-2 text-primary"></i>Common Currencies
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-sm table-hover mb-0" style="font-size:13px">
                        <thead class="table-light">
                            <tr><th>Code</th><th>Symbol</th><th>Name</th></tr>
                        </thead>
                        <tbody>
                            @foreach([['USD','$','US Dollar'],['EUR','€','Euro'],['GBP','£','British Pound'],['BDT','৳','Bangladeshi Taka'],['AED','د.إ','UAE Dirham'],['SAR','﷼','Saudi Riyal'],['INR','₹','Indian Rupee'],['JPY','¥','Japanese Yen'],['CNY','¥','Chinese Yuan'],['CAD','$','Canadian Dollar'],['AUD','$','Australian Dollar'],['SGD','$','Singapore Dollar']] as [$code,$sym,$name])
                            <tr>
                                <td><code class="fw-semibold">{{ $code }}</code></td>
                                <td><strong class="text-primary">{{ $sym }}</strong></td>
                                <td class="text-muted">{{ $name }}</td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

{{-- Edit Modal --}}
<div class="modal fade" id="editCurModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-semibold"><i class="bi bi-pencil me-2 text-primary"></i>Edit Currency</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body pt-2">
                <form method="POST" id="editCurForm">
                @csrf @method('PUT')
                <div class="row g-3">
                    <div class="col-8">
                        <label class="form-label fw-semibold">Name <span class="text-danger">*</span></label>
                        <input type="text" name="name" id="ecName" class="form-control" required>
                    </div>
                    <div class="col-4">
                        <label class="form-label fw-semibold">Symbol</label>
                        <input type="text" name="symbol" id="ecSymbol" class="form-control" maxlength="10"
                               style="font-size:16px;text-align:center;font-weight:600">
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-semibold">Decimal Places</label>
                        <select name="decimal_places" id="ecDecimals" class="form-select">
                            @foreach([0,1,2,3,4] as $d)<option value="{{ $d }}">{{ $d }}</option>@endforeach
                        </select>
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-semibold">Status</label>
                        <div class="form-check form-switch mt-2">
                            <input class="form-check-input" type="checkbox" name="is_active" value="1" id="ecActive">
                            <label class="form-check-label" for="ecActive">Active</label>
                        </div>
                    </div>
                </div>
                </form>
            </div>
            <div class="modal-footer border-0 pt-0">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary px-4" onclick="document.getElementById('editCurForm').submit()">
                    <i class="bi bi-check-circle me-1"></i>Save Changes
                </button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
document.querySelectorAll('.btn-edit-cur').forEach(btn => {
    btn.addEventListener('click', function() {
        document.getElementById('editCurForm').action = this.dataset.url;
        document.getElementById('ecName').value       = this.dataset.name;
        document.getElementById('ecSymbol').value     = this.dataset.symbol;
        document.getElementById('ecDecimals').value   = this.dataset.decimals;
        document.getElementById('ecActive').checked   = this.dataset.active === '1';
        new bootstrap.Modal(document.getElementById('editCurModal')).show();
    });
});
// Auto-uppercase
const codeInput = document.querySelector('input[name="code"]');
if (codeInput) codeInput.addEventListener('input', function() { this.value = this.value.toUpperCase(); });
</script>
@endpush
