@extends('layouts.app')

@section('content')
    <div class="row mb-4">
        <div class="col-12">
            <h2 class="fw-light">Create Subscription</h2>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
                    <li class="breadcrumb-item"><a href="{{ route('accounting.recurring.index') }}">Subscriptions</a></li>
                    <li class="breadcrumb-item active">Create</li>
                </ol>
            </nav>
        </div>
    </div>

    <div class="form-container">
        <form action="{{ route('accounting.recurring.store') }}" method="POST" id="subscriptionForm">
            @csrf
            <div class="row">
                <!-- Left Column: Settings -->
                <div class="col-lg-4">
                    <div class="card mb-4">
                        <div class="card-header bg-dark border-secondary">
                            <h5 class="mb-0">Settings</h5>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label class="form-label">Subscription Title <span class="text-danger">*</span></label>
                                <input type="text" name="title" class="form-control" placeholder="e.g. Monthly Retainer"
                                    required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Customer <span class="text-danger">*</span></label>
                                <select name="customer_id" class="form-select" required>
                                    <option value="">Select Customer</option>
                                    @foreach($customers as $customer)
                                        <option value="{{ $customer->id }}">{{ $customer->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Frequency <span class="text-danger">*</span></label>
                                <select name="frequency" class="form-select" required>
                                    <option value="monthly">Monthly</option>
                                    <option value="yearly">Yearly</option>
                                    <option value="quarterly">Quarterly</option>
                                    <option value="weekly">Weekly</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Start Date <span class="text-danger">*</span></label>
                                <input type="date" name="start_date" class="form-control" value="{{ date('Y-m-d') }}"
                                    required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Notes</label>
                                <textarea name="notes" class="form-control" rows="2"></textarea>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Right Column: Line Items -->
                <div class="col-lg-8">
                    <div class="card mb-4">
                        <div class="card-header bg-dark border-secondary">
                            <h5 class="mb-0">Line Items</h5>
                        </div>
                        <div class="card-body">
                            <table class="table table-bordered border-secondary" id="itemsTable">
                                <thead>
                                    <tr>
                                        <th width="50%">Description</th>
                                        <th width="15%">Qty</th>
                                        <th width="20%">Price</th>
                                        <th width="15%">Total</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr class="item-row">
                                        <td>
                                            <input type="text" name="items[0][description]" class="form-control"
                                                placeholder="Item description" list="productList" onchange="fillPrice(this)"
                                                required>
                                        </td>
                                        <td>
                                            <input type="number" name="items[0][quantity]" class="form-control qty"
                                                value="1" min="0.1" step="0.1" onchange="calcRow(this)" required>
                                        </td>
                                        <td>
                                            <input type="number" name="items[0][unit_price]" class="form-control price"
                                                value="0" min="0" step="0.01" onchange="calcRow(this)" required>
                                        </td>
                                        <td>
                                            <span class="row-total text-white">0.00</span>
                                        </td>
                                        <td>
                                            <button type="button" class="btn btn-danger btn-sm"
                                                onclick="removeRow(this)">x</button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>

                            <datalist id="productList">
                                @foreach($products as $product)
                                    <option value="{{ $product->name }}" data-price="{{ $product->price }}">
                                @endforeach
                            </datalist>

                            <button type="button" class="btn btn-outline-info btn-sm" onclick="addRow()">+ Add Item</button>
                        </div>
                        <div class="card-footer border-secondary text-end">
                            <h4 class="mb-0">Total: <span id="grandTotal" class="text-primary">0.00</span></h4>
                        </div>
                    </div>

                    <div class="text-end">
                        <button type="submit" class="btn btn-success btn-lg">Create Subscription</button>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <script>
        let rowCount = 1;

        function addRow() {
            const table = document.getElementById('itemsTable').getElementsByTagName('tbody')[0];
            const newRow = table.rows[0].cloneNode(true);

            // Reset values
            const inputs = newRow.getElementsByTagName('input');
            for (let i = 0; i < inputs.length; i++) {
                inputs[i].value = (inputs[i].getAttribute('type') === 'number') ? (inputs[i].classList.contains('qty') ? 1 : 0) : '';
                // Update names
                let name = inputs[i].getAttribute('name');
                inputs[i].setAttribute('name', name.replace(/\[\d+\]/, '[' + rowCount + ']'));
            }

            newRow.querySelector('.row-total').innerText = '0.00';
            table.appendChild(newRow);
            rowCount++;
        }

        function removeRow(btn) {
            const row = btn.parentNode.parentNode;
            if (document.querySelectorAll('.item-row').length > 1) {
                row.parentNode.removeChild(row);
                calcTotal();
            }
        }

        function calcRow(el) {
            const row = el.parentNode.parentNode;
            const qty = parseFloat(row.querySelector('.qty').value) || 0;
            const price = parseFloat(row.querySelector('.price').value) || 0;
            const total = qty * price;
            row.querySelector('.row-total').innerText = total.toFixed(2);
            calcTotal();
        }

        function calcTotal() {
            let total = 0;
            document.querySelectorAll('.item-row').forEach(row => {
                const rowVal = parseFloat(row.querySelector('.row-total').innerText) || 0;
                total += rowVal;
            });
            document.getElementById('grandTotal').innerText = total.toFixed(2);
        }

        function fillPrice(input) {
            const val = input.value;
            const list = document.getElementById('productList');
            const options = list.options;
            for (let i = 0; i < options.length; i++) {
                if (options[i].value === val) {
                    const price = options[i].getAttribute('data-price');
                    const row = input.parentNode.parentNode;
                    row.querySelector('.price').value = price;
                    calcRow(input);
                    break;
                }
            }
        }
    </script>
@endsection