@extends('layouts.master')

@section('content')
    <!-- Breadcrumb and Page Title -->
    <div class="az-content-breadcrumb">
        <span>Purchase Orders</span>
        <span>Edit PO</span>
    </div>
    <h2 class="az-content-title" style="display: inline">
        Edit Purchase Order
        <span>
            <a href="{{ route('sales.list') }}" class="btn border" style="float: right">
                <i class="fa-solid fa-bars-staggered"></i> Back to List
            </a>
        </span>
    </h2>

    <div class="row">
        <div class="col-md-12 col-lg-12 col-xl-12">
            <div class="card card-body pd-40">
                <h5 class="card-title mg-b-20">Edit Purchase Order</h5>
                <form action="{{ url('po/update/' . \Crypt::encrypt($purchase_order->id_purchase_order)) }}" method="POST">

                    @csrf
                    @method('PUT')

                    <!-- Error Display -->
                    @if (count($errors) > 0)
                        <div class="p-1">
                            @foreach ($errors->all() as $error)
                                <div class="alert alert-warning alert-danger fade show" role="alert">
                                    {{ $error }}
                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                            @endforeach
                        </div>
                    @endif

                    <div class="row row-sm mg-b-20">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="az-content-label" for="po_date">Date</label>
                                <input type="text" class="form-control" name="po_date" id="po_date"
                                    value="{{ old('po_date', $purchase_order->po_date) }}" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="az-content-label" for="po_no">PONo</label>
                                <input type="text" class="form-control" name="po_no" id="po_no"
                                    value="{{ old('po_no', $purchase_order->po_no) }}" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="az-content-label" for="supplier">Supplier</label>
                                <select class="form-control" name="supplier_id" id="supplier" required>
                                    <option value="">- Select -</option>
                                    @foreach ($suppliers as $sup)
                                        <option value="{{ $sup->id_supplier }}"
                                            {{ $purchase_order->supplier_id == $sup->id_supplier ? 'selected' : '' }}>
                                            {{ $sup->supplier_name }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4 mt-3">
                            <label class="az-content-label" for="po_status">Status</label>
                            <select id="po_status" name="po_status" class="form-control">
                                <option value="1" {{ $purchase_orderdet->status == 1 ? 'selected' : '' }}>Active
                                </option>
                                <option value="0" {{ $purchase_orderdet->status == 0 ? 'selected' : '' }}>
                                    In-Active
                                </option>
                            </select>
                            @error('po_status')
                                <span class="form-text text-danger">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>
                        <div class="col-md-4 mt-3">
                            <div class="form-group">
                                <label class="az-content-label" for="details">Details</label>
                                <textarea class="form-control" name="details" id="details" cols="5" rows="5">{{ old('details', $purchase_order->details) }}</textarea>
                            </div>
                        </div>

                        <!-- Item Details Section -->
                        <div class="col-md-12 mt-5">
                            <h4>Item Details</h4>
                            <div class="shadow p-3 bg-light rounded">
                                <table class="table table-bordered" id="item-table">
                                    <thead>
                                        <tr>
                                            <th>Item</th>
                                            <th>Marka</th>
                                            <th>Bori</th>
                                            <th>Weight</th>
                                            <th>Rate</th>
                                            <th>Amount</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach ($purchase_order->Purchasedetails as $item)
                                            <tr>
                                                <td><input type="text" class="form-control" name="items_name[]"
                                                        value="{{ $item->items_name }}" required></td>
                                                <td><input type="text" class="form-control" name="marka[]"
                                                        value="{{ $item->marka }}" required></td>
                                                <td><input type="number" class="form-control" name="bori[]"
                                                        value="{{ $item->bori }}" required></td>
                                                <td><input type="number" class="form-control" name="weight[]"
                                                        value="{{ $item->weight }}" required></td>
                                                <td><input type="number" class="form-control" name="rate[]"
                                                        value="{{ $item->rate }}" required></td>
                                                <td><input type="number" class="form-control" name="amount[]"
                                                        value="{{ $item->amount }}"></td>
                                                <td>
                                                    <button type="button" class="btn rounded shadow-base"
                                                        onclick="removeRow(this)">
                                                        <i class="text-danger fa-solid fa-trash-can"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                                <button type="button" class="btn btn-az-primary btn-block mt-2" onclick="addRow()">
                                    <span class="mdi mdi-arrow-expand-up"></span> Add More
                                </button>
                            </div>
                        </div>

                    </div>
                    <br>
                    <hr>

                    <!-- Totals Section -->
                    <div class="row mt-4">
                        <div class="col-md-12">
                            <h4>Totals</h4>
                            <div class="form-group row">
                                <label for="total_bori" class="col-sm-2 col-form-label">Total Bori:</label>
                                <div class="col-sm-10">
                                    <input type="number" class="form-control" id="total_bori" name="total_bori"
                                        value="{{ old('total_bori', $purchase_order->total_bori) }}" readonly>
                                </div>
                            </div>
                            <div class="form-group row">
                                <label for="bori_weight" class="col-sm-2 col-form-label">Bori Weight:</label>
                                <div class="col-sm-10">
                                    <input type="number" class="form-control" id="bori_weight" name="bori_weight"
                                        value="{{ old('bori_weight', $purchase_order->bori_weight) }}" readonly>
                                </div>
                            </div>
                            <div class="form-group row">
                                <label for="rent_recieve" class="col-sm-2 col-form-label">Rent Receive:</label>
                                <div class="col-sm-10">
                                    <input type="number" class="form-control" id="rent_recieve" name="rent_recieve"
                                        value="{{ old('rent_recieve', $purchase_order->rent_recieve) }}">
                                </div>
                            </div>
                            <div class="form-group row">
                                <label for="labour" class="col-sm-2 col-form-label">Labour:</label>
                                <div class="col-sm-10">
                                    <input type="number" class="form-control" id="labour" name="labour"
                                        value="{{ old('labour', $purchase_order->labour) }}">
                                </div>
                            </div>
                        </div>
                    </div>

                    <a href="{{ route('sales.list') }}" class="btn btn-danger pd-x-20">Cancel</a>
                    <button type="submit" class="btn btn-az-primary pd-x-20">Update</button>
                </form>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script type="text/javascript">
        $(document).ready(function() {
            var today = new Date().toISOString().split('T')[0];
            $('#po_date').val(today);

            $("#po_date").datepicker({
                dateFormat: "yy-mm-dd"
            });

            // Pre-populate item details and totals
            updateTotals();
        });

        function addRow() {
            var row = `<tr>
                <td>
                   <input type="text" class="form-control" name="items_name[]" id="">
                </td>
                <td>
                   <input type="text" class="form-control" name="marka[]" id="">
                </td>
                <td><input type="number" class="form-control" name="bori[]" required></td>
                <td><input type="number" class="form-control" name="weight[]" required></td>
                <td><input type="number" class="form-control" name="rate[]" required></td>
                <td><input type="number" class="form-control" name="amount[]"></td>
                <td>
                    <button type="button" class="btn rounded shadow-base" onclick="removeRow(this)">
                        <i class="text-danger fa-solid fa-trash-can"></i>
                    </button>
                </td>
            </tr>`;
            $('#item-table tbody').append(row);
        }

        function removeRow(button) {
            $(button).closest('tr').remove();
            updateTotals();
        }

        function handleInputChange() {
            $('#item-table').on('input', 'input[name="bori[]"], input[name="amount[]"], input[name="weight[]"]',
                updateTotals);
            $('#cash_received').on('input', function() {
                let cashReceived = parseFloat($(this).val()) || 0;
                let totalAmount = parseFloat($('#total_amount').val()) || 0;
                $('#remaining_amount').val(totalAmount - cashReceived);
            });
        }

        function updateTotals() {
            let totalBori = 0;
            let totalAmount = 0;
            let boriWeight = 0;

            $('#item-table tbody tr').each(function() {
                let bori = parseFloat($(this).find('input[name="bori[]"]').val()) || 0;
                let amount = parseFloat($(this).find('input[name="amount[]"]').val()) || 0;
                let weight = parseFloat($(this).find('input[name="weight[]"]').val()) || 0;

                totalBori += bori;
                totalAmount += amount;
                boriWeight += weight;
            });

            $('#total_bori').val(totalBori);
            $('#total_amount').val(totalAmount);
            $('#bori_weight').val(boriWeight);

            let cashReceived = parseFloat($('#cash_received').val()) || 0;
            $('#remaining_amount').val(totalAmount - cashReceived);
        }
    </script>
@endpush
