@extends('layouts.master')

@section('title', 'Multi Currency - Daily Rates')

@section('content')
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@400;600;700&family=DM+Sans:wght@300;400;500;600&family=DM+Mono:wght@400&display=swap" rel="stylesheet">

<style>
    :root {
        --sky: #0ea5e9;
        --sky-deep: #0369a1;
        --sky-light: #38bdf8;
        --sky-ghost: rgba(14,165,233,0.07);
        --sky-border: rgba(14,165,233,0.2);

        --white: #ffffff;
        --off: #f7fbff;
        --surface: #eef6fd;
        --border: #daeaf8;

        --ink: #0c0f14;
        --ink-mid: rgba(3,105,161,0.9);

        --fd: 'Cormorant Garamond', Georgia, serif;
        --fb: 'DM Sans', system-ui, sans-serif;
        --fm: 'DM Mono', monospace;

        --ease: cubic-bezier(0.22, 1, 0.36, 1);
        --shadow: 0 10px 40px rgba(14,165,233,0.13), 0 4px 12px rgba(0,0,0,0.06);
        --shadow-md: 0 8px 24px rgba(14,165,233,0.10);
    }

    .main-content { background: var(--off); font-family: var(--fb); }

    .tx-page { max-width: 1100px; margin: 0 auto; padding: 44px 24px 72px; animation: pageIn 0.55s var(--ease) both; }
    @keyframes pageIn { from { opacity: 0; transform: translateY(18px); } to { opacity: 1; transform: translateY(0); } }

    .tx-breadcrumb {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 12px;
        font-weight: 600;
        color: rgba(3,105,161,0.55);
        letter-spacing: 0.05em;
        text-transform: uppercase;
        margin-bottom: 22px;
    }
    .tx-breadcrumb a { color: rgba(3,105,161,0.55); text-decoration: none; }
    .tx-breadcrumb a:hover { color: var(--sky); }
    .tx-breadcrumb .sep { font-size: 10px; color: rgba(3,105,161,0.28); }
    .tx-breadcrumb .current { color: var(--sky-deep); }

    .tx-hero {
        background: linear-gradient(135deg, var(--sky-deep) 0%, var(--sky) 65%, var(--sky-light) 100%);
        border-radius: 22px;
        padding: 30px 36px;
        color: var(--white);
        box-shadow: var(--shadow);
        margin-bottom: 18px;
        position: relative;
        overflow: hidden;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 18px;
    }
    .tx-hero::before {
        content: '';
        position: absolute;
        inset: 0;
        background-image: repeating-linear-gradient(-45deg, rgba(255,255,255,0.04) 0px, rgba(255,255,255,0.04) 1px, transparent 1px, transparent 14px);
        pointer-events: none;
    }

    .hero-text { position: relative; z-index: 1; }
    .hero-text h1 { margin: 0; font-family: var(--fd); font-size: 40px; line-height: 1.05; }
    .hero-text p { margin: 6px 0 0; font-size: 13px; color: rgba(255,255,255,0.94); }

    .hero-stat {
        position: relative;
        z-index: 1;
        background: rgba(255,255,255,0.18);
        border: 1px solid rgba(255,255,255,0.35);
        border-radius: 14px;
        padding: 14px 18px;
        text-align: center;
        min-width: 140px;
    }
    .hero-stat .val { font-family: var(--fd); font-weight: 700; font-size: 30px; line-height: 1; }
    .hero-stat .lab { font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; margin-top: 4px; }

    .toolbar {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 12px;
        flex-wrap: wrap;
        margin: 14px 0 18px;
    }
    .toolbar-left { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
    .toolbar-right { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }

    .btnx {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 10px 16px;
        border-radius: 10px;
        border: 1px solid var(--sky-border);
        background: var(--white);
        color: var(--sky-deep);
        text-decoration: none;
        font-weight: 700;
        font-size: 13px;
        transition: transform 160ms var(--ease), box-shadow 160ms var(--ease), background 160ms var(--ease);
        user-select: none;
    }
    .btnx.primary {
        background: linear-gradient(135deg, var(--sky-deep), var(--sky));
        color: var(--white);
        border-color: var(--sky-deep);
    }
    .btnx:hover { transform: translateY(-1px); box-shadow: var(--shadow-md); }

    .search-wrap { position: relative; }
    .search-icon { position: absolute; left: 12px; top: 9px; color: var(--sky-deep); }
    .search-wrap input {
        width: 320px;
        max-width: 100%;
        padding: 10px 14px 10px 34px;
        border: 1px solid var(--border);
        border-radius: 10px;
        background: var(--white);
        color: var(--ink);
        font-size: 13px;
        outline: none;
    }
    .search-wrap input:focus { border-color: var(--sky); box-shadow: 0 0 0 3px rgba(14,165,233,0.12); }

    .notice {
        background: var(--sky-ghost);
        border: 1px solid var(--sky-border);
        color: var(--sky-deep);
        border-radius: 14px;
        padding: 12px 14px;
        margin-bottom: 12px;
        font-weight: 600;
    }

    .tx-card {
        background: var(--white);
        border: 1px solid var(--border);
        border-radius: 16px;
        box-shadow: var(--shadow-md);
        overflow: hidden;
        margin-bottom: 14px;
    }
    .tx-card-head { padding: 14px 16px; background: var(--surface); border-bottom: 1px solid var(--border); }
    .tx-card-head h2 { margin: 0; font-family: var(--fd); font-weight: 700; color: var(--sky-deep); font-size: 18px; }
    .tx-card-body { padding: 16px; }

    .form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 12px; }
    .field label {
        display: block;
        font-size: 12px;
        font-weight: 700;
        letter-spacing: 0.04em;
        text-transform: uppercase;
        color: rgba(3,105,161,0.8);
        margin-bottom: 6px;
    }
    .field input,
    .field select {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid var(--border);
        border-radius: 10px;
        font-size: 14px;
        outline: none;
        background: var(--white);
        color: var(--ink);
    }
    .field input:focus,
    .field select:focus { border-color: var(--sky); box-shadow: 0 0 0 3px rgba(14,165,233,0.12); }

    .form-actions { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 12px; }

    .tx-table-card {
        background: var(--white);
        border: 1px solid var(--border);
        border-radius: 16px;
        overflow: hidden;
        box-shadow: var(--shadow-md);
    }
    .table-head-row {
        display: grid;
        grid-template-columns: 160px 1fr 1fr 140px 140px 180px 1fr;
        gap: 10px;
        padding: 14px 16px;
        background: var(--surface);
        border-bottom: 1px solid var(--border);
        font-size: 12px;
        font-weight: 800;
        color: rgba(3,105,161,0.85);
        text-transform: uppercase;
        letter-spacing: 0.06em;
    }
    .tx-row {
        display: grid;
        grid-template-columns: 160px 1fr 1fr 140px 140px 180px 1fr;
        gap: 10px;
        padding: 14px 16px;
        border-bottom: 1px solid var(--border);
        align-items: center;
    }
    .tx-row:hover { background: var(--sky-ghost); }
    .tx-row:last-child { border-bottom: none; }

    .mono { font-family: var(--fm); }
    .muted { color: rgba(3,105,161,0.72); font-size: 12px; margin-top: 2px; }

    .pill {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        padding: 6px 10px;
        border-radius: 999px;
        border: 1px solid var(--sky-border);
        background: var(--sky-ghost);
        color: var(--sky-deep);
        font-family: var(--fm);
        font-size: 12px;
        font-weight: 700;
        white-space: nowrap;
    }

    .cell-actions { display: flex; gap: 8px; justify-content: flex-end; flex-wrap: wrap; }
    .act-btn {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 9px 10px;
        border-radius: 10px;
        border: 1px solid var(--sky-border);
        background: var(--white);
        color: var(--sky-deep);
        font-weight: 800;
        font-size: 12px;
        text-decoration: none;
        cursor: pointer;
        user-select: none;
    }
    .act-btn:hover { background: var(--sky-ghost); }
    .act-primary { background: linear-gradient(135deg, var(--sky-deep), var(--sky)); color: var(--white); border-color: var(--sky-deep); }

    .empty-row { padding: 26px 16px; text-align: center; color: rgba(3,105,161,0.85); }
    .empty-icon { font-size: 34px; margin-bottom: 6px; }
    .empty-title { font-family: var(--fd); font-size: 18px; font-weight: 700; }
    .empty-sub { font-size: 13px; opacity: 0.9; margin-top: 3px; }
    .no-results-row { display: none; padding: 12px 16px; border-top: 1px dashed var(--border); background: var(--white); color: rgba(3,105,161,0.8); text-align: center; font-weight: 700; }

    .modal-overlay {
        position: fixed;
        inset: 0;
        background: rgba(14,165,233,0.14);
        display: none;
        align-items: center;
        justify-content: center;
        padding: 20px;
        z-index: 9999;
    }
    .modal {
        width: 100%;
        max-width: 460px;
        background: var(--white);
        border: 1px solid var(--sky-border);
        border-radius: 18px;
        box-shadow: var(--shadow);
        padding: 18px;
        text-align: center;
    }
    .modal-icon { font-size: 34px; }
    .modal-title { font-family: var(--fd); font-weight: 700; color: var(--sky-deep); font-size: 22px; margin-top: 6px; }
    .modal-body { color: rgba(3,105,161,0.9); font-size: 13px; margin-top: 8px; line-height: 1.4; }
    .modal-actions { display: flex; gap: 10px; justify-content: center; margin-top: 14px; flex-wrap: wrap; }
    .modal-actions button { min-width: 120px; }

    @media (max-width: 920px) {
        .table-head-row { display: none; }
        .tx-row { grid-template-columns: 1fr; gap: 8px; }
        .cell-actions { justify-content: flex-start; }
    }
    @media (max-width: 760px) {
        .tx-hero { padding: 24px 20px; flex-direction: column; align-items: flex-start; }
        .hero-text h1 { font-size: 32px; }
        .hero-stat { width: 100%; }
        .search-wrap input { width: 100%; }
    }
</style>

<div class="tx-page">
    <nav class="tx-breadcrumb">
        <a href="{{ route('modules.edit') }}">Edit Menu</a>
        <span class="sep">›</span>
        <a href="{{ route('modules.edit.multi-currency') }}">Multi Currency</a>
        <span class="sep">›</span>
        <span class="current">Daily Rates</span>
    </nav>

    <div class="tx-hero">
        <div class="hero-text">
            <h1>Daily Rates</h1>
            <p>Capture and update daily exchange rates.</p>
        </div>
        <div class="hero-stat">
            <div class="val">{{ count($rates ?? []) }}</div>
            <div class="lab">Rates</div>
        </div>
    </div>

    <div class="toolbar">
        <div class="toolbar-left">
            <a href="{{ route('modules.edit.multi-currency') }}" class="btnx">← Back</a>
            <a href="{{ route('modules.edit') }}" class="btnx">Edit Menu</a>
            <button type="button" class="btnx primary" onclick="refreshRate()">+ New Rate</button>
        </div>
        <div class="toolbar-right">
            <div class="search-wrap">
                <span class="search-icon">🔍</span>
                <input type="search" id="searchInput" placeholder="Search rates...">
            </div>
        </div>
    </div>

    @if (session('rate_success'))
        <div class="notice" id="successNotice">{{ session('rate_success') }}</div>
    @endif

    @if ($errors->any())
        <div class="notice" id="errorNotice">
            @foreach ($errors->all() as $error)
                <div>{{ $error }}</div>
            @endforeach
        </div>
    @endif

    <div class="tx-card">
        <div class="tx-card-head">
            <h2 id="formHeader_rates">Add Daily Rate</h2>
        </div>
        <div class="tx-card-body">
            <form action="{{ route('rate.store') }}" method="post" id="ratesForm">
                @csrf
                <input type="hidden" id="rateId" name="id" value="">
                <input type="hidden" name="_method" value="POST" id="rateMethod">

                <div class="form-grid">
                    <div class="field">
                        <label for="base_currency">Base Currency</label>
                        <select id="base_currency" name="base_currency" required>
                            <option value="" disabled selected>Select Base Currency</option>
                            @foreach ($allCurrencies as $allCurrency)
                                <option value="{{ $allCurrency->currency_id }}">{{ $allCurrency->currency_name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="field">
                        <label for="target_currency">Target Currency</label>
                        <select id="target_currency" name="target_currency" required>
                            <option value="" disabled selected>Select Target Currency</option>
                            @foreach ($allCurrencies as $allCurrency)
                                <option value="{{ $allCurrency->currency_id }}">{{ $allCurrency->currency_name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="field">
                        <label for="rate_date">Rate Date</label>
                        <input type="date" id="rate_date" name="rate_date" value="{{ old('rate_date', date('Y-m-d')) }}" required>
                    </div>
                    <div class="field">
                        <label for="buy_rate">Buy Rate</label>
                        <input type="number" step="0.000001" id="buy_rate" name="buy_rate" placeholder="0.000000" value="{{ old('buy_rate') }}" required>
                    </div>
                    <div class="field">
                        <label for="sell_rate">Sell Rate</label>
                        <input type="number" step="0.000001" id="sell_rate" name="sell_rate" placeholder="0.000000" value="{{ old('sell_rate') }}" required>
                    </div>
                    <div class="field">
                        <label for="source">Source</label>
                        <input type="text" id="source" name="source" placeholder="Optional" value="{{ old('source') }}">
                    </div>
                </div>

                <div class="form-actions">
                    <button type="submit" class="act-btn act-primary" id="submitButton_rates">✓ Create</button>
                    <button type="button" class="act-btn" onclick="refreshRate()">↺ Refresh</button>
                </div>
            </form>
        </div>
    </div>

    <div class="tx-table-card">
        <div class="table-head-row">
            <div>Date</div>
            <div>Base</div>
            <div>Target</div>
            <div>Buy</div>
            <div>Sell</div>
            <div>Source</div>
            <div style="text-align:right;">Actions</div>
        </div>

        <div id="rateRows">
            @forelse ($rates as $rate)
                @if($rate->rate_id)
                    <div class="tx-row" data-search="{{ strtolower(($rate->rate_date ?? '').' '.($rate->baseCurrency?->currency_name ?? '').' '.($rate->targetCurrency?->currency_name ?? '').' '.($rate->buy_rate ?? '').' '.($rate->sell_rate ?? '').' '.($rate->source ?? '')) }}">
                        <div><span class="pill mono">{{ $rate->rate_date }}</span></div>
                        <div>
                            <div style="font-weight:800;color:var(--sky-deep);">{{ $rate->baseCurrency?->currency_name ?? '' }}</div>
                            <div class="muted">{{ ($rate->baseCurrency?->symbol ?? '').' '.($rate->baseCurrency?->currency_code ?? '') }}</div>
                        </div>
                        <div>
                            <div style="font-weight:800;color:var(--sky-deep);">{{ $rate->targetCurrency?->currency_name ?? '' }}</div>
                            <div class="muted">{{ ($rate->targetCurrency?->symbol ?? '').' '.($rate->targetCurrency?->currency_code ?? '') }}</div>
                        </div>
                        <div class="mono">{{ $rate->buy_rate }}</div>
                        <div class="mono">{{ $rate->sell_rate }}</div>
                        <div class="mono">{{ $rate->source ?: '-' }}</div>
                        <div class="cell-actions">
                            <button
                                type="button"
                                class="act-btn"
                                onclick="editRate(event, {{ (int) $rate->rate_id }}, {{ (int) $rate->base_currency_id }}, {{ (int) $rate->target_currency_id }}, @js($rate->rate_date), @js($rate->buy_rate), @js($rate->sell_rate), @js($rate->source))"
                            >✎ Edit</button>
                            <button
                                type="button"
                                class="act-btn"
                                data-action="{{ route('rate.delete', $rate->rate_id) }}"
                                data-name="Rate {{ $rate->rate_date }}"
                                onclick="confirmDelete(this.dataset.action, this.dataset.name)"
                            >✕ Delete</button>
                        </div>
                    </div>
                @endif
            @empty
                <div class="empty-row">
                    <div class="empty-icon">📈</div>
                    <div class="empty-title">No rates found</div>
                    <div class="empty-sub">Create your first daily rate to get started.</div>
                </div>
            @endforelse

            <div class="no-results-row" id="noResults">No rates match your search.</div>
        </div>
    </div>
</div>

<div id="deleteModal" class="modal-overlay" aria-hidden="true">
    <div class="modal" role="dialog" aria-modal="true" aria-labelledby="deleteTitle">
        <div class="modal-icon">🗑</div>
        <div class="modal-title" id="deleteTitle">Delete Rate?</div>
        <div class="modal-body">
            You are about to delete <strong id="deleteName"></strong>. This action cannot be undone.
        </div>
        <div class="modal-actions">
            <button type="button" class="act-btn" onclick="closeModal()">Cancel</button>
            <button type="button" class="act-btn act-primary" onclick="submitDelete()">Delete</button>
        </div>
    </div>
</div>

<form id="deleteForm" method="POST" style="display:none;">
    @csrf
    @method('DELETE')
</form>

<script>
(() => {
    const input = document.getElementById('searchInput');
    const wrap = document.getElementById('rateRows');
    const noResults = document.getElementById('noResults');

    function filterRows() {
        const q = (input.value || '').trim().toLowerCase();
        const rows = Array.from(wrap.querySelectorAll('.tx-row'));
        let visible = 0;

        rows.forEach((row) => {
            const hit = !q || (row.dataset.search || '').includes(q);
            row.style.display = hit ? '' : 'none';
            if (hit) visible++;
        });

        if (noResults) noResults.style.display = (q && visible === 0) ? 'block' : 'none';
    }

    if (input) input.addEventListener('input', filterRows);
})();

let _deleteAction = null;
function confirmDelete(action, name) {
    _deleteAction = action;
    document.getElementById('deleteName').textContent = name || '';
    const modal = document.getElementById('deleteModal');
    modal.style.display = 'flex';
    modal.setAttribute('aria-hidden', 'false');
}

function closeModal() {
    const modal = document.getElementById('deleteModal');
    modal.style.display = 'none';
    modal.setAttribute('aria-hidden', 'true');
    _deleteAction = null;
}

function submitDelete() {
    if (!_deleteAction) return;
    const form = document.getElementById('deleteForm');
    form.action = _deleteAction;
    form.submit();
}

function editRate(event, id, baseCurrency, targetCurrency, rateDate, buyRate, sellRate, source) {
    event.preventDefault();
    document.getElementById('rateId').value = id || '';
    document.getElementById('base_currency').value = baseCurrency || '';
    document.getElementById('target_currency').value = targetCurrency || '';
    document.getElementById('rate_date').value = rateDate || '{{ date('Y-m-d') }}';
    document.getElementById('buy_rate').value = buyRate || '';
    document.getElementById('sell_rate').value = sellRate || '';
    document.getElementById('source').value = source || '';
    document.getElementById('formHeader_rates').innerText = 'Edit Daily Rate';
    document.getElementById('submitButton_rates').innerText = '✓ Update';
    document.getElementById('ratesForm').action = '{{ route("rate.update") }}';
    document.getElementById('rateMethod').value = 'PUT';
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

function refreshRate() {
    document.getElementById('rateId').value = '';
    document.getElementById('base_currency').value = '';
    document.getElementById('target_currency').value = '';
    document.getElementById('rate_date').value = '{{ date('Y-m-d') }}';
    document.getElementById('buy_rate').value = '';
    document.getElementById('sell_rate').value = '';
    document.getElementById('source').value = '';
    document.getElementById('formHeader_rates').innerText = 'Add Daily Rate';
    document.getElementById('submitButton_rates').innerText = '✓ Create';
    document.getElementById('ratesForm').action = '{{ route("rate.store") }}';
    document.getElementById('rateMethod').value = 'POST';

    const s = document.getElementById('successNotice');
    const e = document.getElementById('errorNotice');
    if (s) s.style.display = 'none';
    if (e) e.style.display = 'none';
}
</script>
@endsection
