@extends('layouts.admin')

@section('title', 'Salesman Performance Report')

@section('content')
<x-admin.report-page title="Salesman Performance Report" subtitle="POS salesman sales, profit, discounts, and share of total.">
    <x-slot:actions>
        <a href="{{ route('admin.reports.salesman.export-csv', request()->only(['start_date', 'end_date', 'period', 'staff_id', 'location_id'])) }}" class="ci-btn ci-btn--ghost">
            <i class="bi bi-download"></i> Export CSV
        </a>
        @can('reports.profit')
        <a href="{{ route('admin.reports.profit') }}" class="ci-btn ci-btn--ghost">
            <i class="bi bi-graph-up"></i> Profit Reports
        </a>
        @endcan
    </x-slot:actions>

    <form method="GET" action="{{ route('admin.reports.salesman') }}" class="ci-filters ci-filters--report">
        @include('admin.reports.partials.location-filter', ['ci' => true])
        <div class="ci-filters__field">
            <label for="period">Period</label>
            <select name="period" id="period" onchange="toggleCustomDates()">
                <option value="day" {{ $period === 'day' ? 'selected' : '' }}>Today</option>
                <option value="week" {{ $period === 'week' ? 'selected' : '' }}>This Week</option>
                <option value="month" {{ $period === 'month' ? 'selected' : '' }}>This Month</option>
                <option value="year" {{ $period === 'year' ? 'selected' : '' }}>This Year</option>
                <option value="custom" {{ $period === 'custom' ? 'selected' : '' }}>Custom Range</option>
            </select>
        </div>

        <div class="ci-filters__field" id="startDateDiv" style="{{ $period === 'custom' ? '' : 'display: none;' }}">
            <label for="start_date">Start Date</label>
            <input type="date" name="start_date" id="start_date" value="{{ $startDate }}">
        </div>

        <div class="ci-filters__field" id="endDateDiv" style="{{ $period === 'custom' ? '' : 'display: none;' }}">
            <label for="end_date">End Date</label>
            <input type="date" name="end_date" id="end_date" value="{{ $endDate }}">
        </div>

        <div class="ci-filters__field">
            <label for="staff_id">Salesman</label>
            <select name="staff_id" id="staff_id">
                <option value="">All Salesmen</option>
                @foreach($staff as $member)
                    <option value="{{ $member->id }}" {{ $staffId == $member->id ? 'selected' : '' }}>
                        {{ $member->name }}
                    </option>
                @endforeach
            </select>
        </div>

        <div class="ci-filters__actions">
            <button type="submit" class="ci-btn ci-btn--primary">
                <i class="bi bi-search"></i> Filter
            </button>
        </div>
    </form>

    <div class="ci-stats">
        <div class="ci-stat">
            <div>
                <p class="ci-stat__label">Total Sales</p>
                <p class="ci-stat__value ci-money">₹{{ number_format($totalSales, 2) }}</p>
                <p class="ci-stat__meta">{{ $totalOrders }} orders</p>
            </div>
            <span class="ci-stat__icon"><i class="bi bi-currency-rupee"></i></span>
        </div>

        <div class="ci-stat">
            <div>
                <p class="ci-stat__label">Total Profit</p>
                <p class="ci-stat__value ci-money">₹{{ number_format($totalProfit, 2) }}</p>
                <p class="ci-stat__meta">
                    @if($totalSales > 0)
                        {{ number_format(($totalProfit / $totalSales) * 100, 1) }}% margin
                    @else
                        0% margin
                    @endif
                </p>
            </div>
            <span class="ci-stat__icon"><i class="bi bi-graph-up"></i></span>
        </div>

        <div class="ci-stat">
            <div>
                <p class="ci-stat__label">Total Orders</p>
                <p class="ci-stat__value">{{ number_format($totalOrders) }}</p>
                <p class="ci-stat__meta">
                    @if($totalOrders > 0)
                        ₹{{ number_format($totalSales / $totalOrders, 0) }} avg
                    @else
                        ₹0 avg
                    @endif
                </p>
            </div>
            <span class="ci-stat__icon"><i class="bi bi-receipt"></i></span>
        </div>

        <div class="ci-stat">
            <div>
                <p class="ci-stat__label">Total Discounts</p>
                <p class="ci-stat__value ci-money">₹{{ number_format($totalDiscounts, 2) }}</p>
                <p class="ci-stat__meta">
                    @if($totalSales > 0)
                        {{ number_format(($totalDiscounts / ($totalSales + $totalDiscounts)) * 100, 1) }}% of gross
                    @else
                        0% of gross
                    @endif
                </p>
            </div>
            <span class="ci-stat__icon"><i class="bi bi-percent"></i></span>
        </div>
    </div>

    <div class="ci-section">
        <div class="ci-section__head">
            <h5>
                <i class="bi bi-people"></i> Salesman Performance
                <small class="text-muted">({{ $startDate }} to {{ $endDate }})</small>
            </h5>
        </div>
        <div class="ci-section__body--flush">
            <div class="ci-table-card" style="border:0;border-radius:0;box-shadow:none;">
                <div class="ci-table-wrap">
                    <table class="ci-table">
                        <thead>
                            <tr>
                                <th>Salesman</th>
                                <th class="ci-end">Orders</th>
                                <th class="ci-end">Total Sales</th>
                                <th class="ci-end">Total Profit</th>
                                <th class="ci-end">Profit Margin</th>
                                <th class="ci-end">Avg Order Value</th>
                                <th class="ci-end">Total Discounts</th>
                                <th>Performance</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($salesmanData as $data)
                                <tr>
                                    <td>
                                        <div>
                                            <strong>{{ $data['staff_name'] }}</strong>
                                            @if($data['staff_email'])
                                                <br><small class="text-muted">{{ $data['staff_email'] }}</small>
                                            @endif
                                        </div>
                                    </td>
                                    <td class="ci-end">
                                        <span class="ci-pill ci-pill--count">{{ $data['total_orders'] }}</span>
                                    </td>
                                    <td class="ci-end ci-money">
                                        ₹{{ number_format($data['total_sales'], 2) }}
                                    </td>
                                    <td class="ci-end ci-money" style="color:var(--ci-success);">
                                        ₹{{ number_format($data['total_profit'], 2) }}
                                    </td>
                                    <td class="ci-end">
                                        @if($data['profit_margin'] > 0)
                                            <span class="ci-pill ci-pill--success">{{ number_format($data['profit_margin'], 1) }}%</span>
                                        @else
                                            <span class="ci-pill ci-pill--inactive">0%</span>
                                        @endif
                                    </td>
                                    <td class="ci-end ci-money">₹{{ number_format($data['avg_order_value'], 2) }}</td>
                                    <td class="ci-end ci-money">₹{{ number_format($data['total_discounts'], 2) }}</td>
                                    <td>
                                        @php
                                            $performance = $totalSales > 0 ? ($data['total_sales'] / $totalSales) * 100 : 0;
                                        @endphp
                                        <div class="progress" style="height: 20px;">
                                            <div class="progress-bar
                                                @if($performance >= 30) bg-success
                                                @elseif($performance >= 15) bg-warning
                                                @else bg-danger
                                                @endif"
                                                role="progressbar"
                                                style="width: {{ min($performance, 100) }}%"
                                                aria-valuenow="{{ $performance }}"
                                                aria-valuemin="0"
                                                aria-valuemax="100">
                                                {{ number_format($performance, 1) }}%
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="8">
                                        <div class="ci-empty">
                                            <i class="bi bi-people"></i>
                                            <h3>No Salesman Data Found</h3>
                                            <p>No POS sales found for the selected period and filters.</p>
                                            @can('pos_access')
                                            <a href="{{ route('admin.pos.index') }}" class="ci-btn ci-btn--primary" target="_blank">
                                                <i class="bi bi-cash-stack"></i> Open POS
                                            </a>
                                            @endcan
                                        </div>
                                    </td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</x-admin.report-page>
@endsection

@push('scripts')
<script>
function toggleCustomDates() {
    const period = document.getElementById('period').value;
    const startDateDiv = document.getElementById('startDateDiv');
    const endDateDiv = document.getElementById('endDateDiv');

    if (period === 'custom') {
        startDateDiv.style.display = 'block';
        endDateDiv.style.display = 'block';
    } else {
        startDateDiv.style.display = 'none';
        endDateDiv.style.display = 'none';
    }
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    toggleCustomDates();
});
</script>
@endpush
