@extends('layouts.app')

@section('main')
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1><i class="fas fa-shopping-cart"></i> Sales Management</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="{{ route('home') }}">Home</a></li>
                        <li class="breadcrumb-item active">Sales</li>
                    </ol>
                </div>
            </div>
        </div>
        
        @if (session('success'))
            <div class="alert alert-success alert-dismissible fade show">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                <i class="fas fa-check-circle"></i> {{ session('success') }}
            </div>
        @endif
        @if (session('error'))
            <div class="alert alert-danger alert-dismissible fade show">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                <i class="fas fa-exclamation-circle"></i> {{ session('error') }}
            </div>
        @endif
    </section>

    <!-- Sales Summary Cards -->
    <section class="content">
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3 id="total-sales">{{ count($sales) }}</h3>
                        <p>Total Sales</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-shopping-cart"></i>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3 id="total-amount">{{ $all_settings->currency ?? 'BDT' }} {{ number_format($totals['total_amount'], 2) }}</h3>
                        <p>Total Amount</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3 id="total-profit">{{ $all_settings->currency ?? 'BDT' }} {{ number_format($totals['total_profit'], 2) }}</h3>
                        <p>Total Profit</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-chart-line"></i>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3 id="total-quantity">{{ $totals['total_sale'] }}</h3>
                        <p>Items Sold</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-box"></i>
                    </div>
                </div>
            </div>
        </div>

        <x-admin-table 
            title="All Sales Transactions"
            :ajax-url="route('sale.index')"
            table-id="sales-table"
            :show-search="true"
            :show-date-filter="true"
            :show-export="true"
            :columns="[
                ['title' => 'SL', 'field' => 'sl', 'orderable' => false],
                ['title' => 'Product', 'field' => 'product_name'],
                ['title' => 'Customer', 'field' => 'customer_name'],
                ['title' => 'Type', 'field' => 'type'],
                ['title' => 'Payment Method', 'field' => 'payment_method'],
                ['title' => 'Unit Price', 'field' => 'sell_price'],
                ['title' => 'Quantity', 'field' => 'sold_quantity'],
                ['title' => 'Total Price', 'field' => 'total_price'],
                ['title' => 'Profit', 'field' => 'profit'],
                ['title' => 'Warranty', 'field' => 'warranty'],
                ['title' => 'Sale Date', 'field' => 'sale_date'],
                ['title' => 'Actions', 'field' => 'actions', 'orderable' => false, 'searchable' => false]
            ]"
        >
            <x-slot name="extraFilters">
                <div class="col-md-2">
                    <label for="type_filter" class="form-label">Type</label>
                    <select class="form-control" id="type_filter" name="type_filter">
                        <option value="">All Types</option>
                        @foreach($types as $type)
                            <option value="{{ $type }}">{{ ucfirst($type) }}</option>
                        @endforeach
                    </select>
                </div>
                
                <div class="col-md-2">
                    <label for="payment_filter" class="form-label">Payment Method</label>
                    <select class="form-control" id="payment_filter" name="payment_filter">
                        <option value="">All Methods</option>
                        @foreach($paymentMethods as $method)
                            <option value="{{ $method }}">{{ ucfirst($method) }}</option>
                        @endforeach
                    </select>
                </div>
            </x-slot>
        </x-admin-table>
    </section>

    @push('script')
    <script>
        // Update summary cards when table data changes
        $(document).on('xhr.dt', '#sales-table', function(e, settings, json) {
            if (json && json.totals) {
                $('#total-sales').text(json.recordsFiltered || 0);
                $('#total-amount').text('{{ $all_settings->currency ?? 'BDT' }} ' + (json.totals.total_amount || 0).toFixed(2));
                $('#total-profit').text('{{ $all_settings->currency ?? 'BDT' }} ' + (json.totals.total_profit || 0).toFixed(2));
                $('#total-quantity').text(json.totals.total_quantity || 0);
            }
        });
    </script>
    @endpush
    <section class="content">
        <div class="card">
            <div class="card-body">
                <div class="row">
                    <div class="col-5">
                        <form method="GET" class="">
                            <label>Select Date Range:</label>
                            <input type="text" name="date_range" id="date_range" class="form-control d-inline w-50"
                                value="{{ request('date_range') }}">
                            <button type="submit" class="btn btn-primary ml-2">Filter</button>
                        </form>
                    </div>
                </div>
                @php
                    $line_total_amount = 0;
                    $total_amount = 0;
                    $total_profit = 0;
                    $line_total_profit = 0;
                @endphp
                <table id="data_table" class="table table-bordered table-striped">
                    <thead>
                        <th>#</th>
                        <th>Customer Name</th>
                        <th>Brand/Tpye</th>
                        <th>Model/Name</th>
                        <th>IMEI/SN</th>
                        <th>Selling Price</th>
                        <th>Quantity</th>
                        <th>Total Amount</th>
                        <th>Profit</th>
                        <th>Sale Date</th>
                        <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($sales as $sale)
                            @php
                                $line_total_amount = $sale->sell_price * $sale->sold_quantity;
                                $line_total_profit = $sale->profit;
                                $total_amount += $line_total_amount;
                                $total_profit += $line_total_profit;
                            @endphp
                            <tr>
                                <td>{{ $sale->id }}</td>
                                <td>{{ htmlspecialchars($sale->customer_name) }}</td>
                                <td>{{ e($sale->product->brand) }}  {{ e($sale->product->type) }}</td>
                                <td>{{ e($sale->product->model) }}  {{ e($sale->product->name) }}</td>
                                <td>{{ htmlspecialchars($sale->product->imei_or_sn) }}</td>
                                <td>{{ $all_settings->currency . ' ' . number_format($sale->sell_price, 2) }}</td>
                                <td>{{ $sale->sold_quantity }}</td>
                                <td>{{ $all_settings->currency . ' ' . number_format($line_total_amount, 2) }}
                                </td>
                                <td>{{ $all_settings->currency . ' ' . number_format($line_total_profit, 2) }}</td>
                                <td>{{ $sale->created_at }}</td>
                                <td>
                                    <div class="btn-group">
                                        <button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown"
                                            aria-haspopup="true" aria-expanded="false">
                                            Action
                                        </button>
                                        <div class="dropdown-menu">
                                            {{-- <a class="dropdown-item"
                                                href="{{ route('sales.show', $sale->id) }}">View Sale</a> --}}
                                            <a class="dropdown-item" href="{{ route('sale.invoice', $sale->id) }}">Print
                                                Invoice</a>
                                            <form action="{{ route('sale.destroy', $sale->id) }}" method="POST"
                                                onsubmit="return confirm('Are you sure you want to delete this sale?')">
                                                @csrf
                                                @method('DELETE')
                                                <button type="submit" class="dropdown-item text-danger">Delete</button>
                                            </form>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                    <tfoot>
                        <tr>
                            <th>#</th>
                            <th>Customer Name</th>
                            <th>Brand</th>
                            <th>Model</th>
                            <th>IMEI/SN</th>
                            <th>Selling Price</th>
                            <th>Quantity</th>
                            <th>Total Amount</th>
                            <th>Profit</th>
                            <th>Sale Date</th>
                            <th>Actions</th>
                        </tr>
                    </tfoot>
                </table>
                <table id="summary_table" class="table table-bordered table-striped mt-3">
                    <thead>
                        <tr>
                            <th>Total Sale</th>
                            <th>Total Amount</th>
                            <th>Total Profit</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td id="total_sales">{{ count($sales) }}</td>
                            <td id="total_sell_amount">{{ $all_settings->currency }}
                                {{ number_format($total_amount, 3) }}
                            </td>
                            <td id="total_profit">{{ $all_settings->currency }} {{ number_format($total_profit, 3) }}</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </section>
@endsection

@push('script')
    <script>
        $(function() {
            $("#data_table").DataTable({
                "responsive": true,
                "lengthChange": true,
                "autoWidth": false,
                "lengthMenu": [
                    [10, 50, 100, 500, -1],
                    [10, 50, 100, 500, "All"]
                ],
                "buttons": ["copy", "csv", "excel", "pdf", "print", "colvis"]
            }).buttons().container().appendTo('#example1_wrapper .col-md-6:eq(0)');

        });
        $(document).ready(function() {

            $('#date_range').daterangepicker({
                autoUpdateInput: false,
                locale: {
                    format: 'YYYY-MM-DD'
                }
            }).on('apply.daterangepicker', function(ev, picker) {
                $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format(
                    'YYYY-MM-DD'));
            });
        });
    </script>
@endpush
