@extends('layouts.app')
@section('title', 'Gross Profit Report')
@section('breadcrumb')
<a href="{{ route('reports.index') }}" class="text-slate-400 hover:text-white">Reports</a>
<span class="text-slate-600 mx-2">/</span>
<span class="text-white">Gross Profit</span>
@endsection

@section('content')

<div class="flex items-center justify-between mb-6">
    <div>
        <h1 class="mb-1">Gross Profit Report</h1>
        <p>Revenue vs costs across all jobs — sorted by profitability</p>
    </div>
    <div class="flex gap-2">
        <a href="{{ route('reports.gross-profit', array_merge(request()->all(), ['export' => 'csv'])) }}"
           class="btn btn-secondary text-sm">
            <i class="fas fa-download"></i> Export CSV
        </a>
    </div>
</div>

<!-- Filters -->
<form method="GET" action="{{ route('reports.gross-profit') }}" class="card p-4 mb-6">
    <div class="grid grid-cols-1 md:grid-cols-6 gap-3 items-end">
        <div>
            <label>From</label>
            <input type="date" name="from" class="input" value="{{ $from->toDateString() }}">
        </div>
        <div>
            <label>To</label>
            <input type="date" name="to" class="input" value="{{ $to->toDateString() }}">
        </div>
        <div>
            <label>Project Manager</label>
            <select name="pm_filter" class="input">
                <option value="">— All PMs —</option>
                @foreach($projectManagers as $pm)
                <option value="{{ $pm->id }}" {{ $pmFilter == $pm->id ? 'selected' : '' }}>{{ $pm->name }}</option>
                @endforeach
            </select>
        </div>
        <div>
            <label>Stage</label>
            <select name="stage_filter" class="input">
                <option value="">— All stages —</option>
                @foreach(['lead','consult','sold','contracts','cm','processing','delivery','installation','completion'] as $s)
                <option value="{{ $s }}" {{ $stageFilter === $s ? 'selected' : '' }}>{{ ucfirst($s) }}</option>
                @endforeach
            </select>
        </div>
        <div>
            <label>Job Number</label>
            <input type="text" name="job_number" class="input" placeholder="e.g. J-0012" value="{{ request('job_number') }}">
        </div>
        <div class="flex gap-2">
            <button type="submit" class="btn btn-primary flex-1">Apply</button>
            <a href="{{ route('reports.gross-profit') }}" class="btn btn-secondary">Reset</a>
        </div>
    </div>
    <input type="hidden" name="sort_by" value="{{ $sortBy }}">
    <input type="hidden" name="sort_dir" value="{{ $sortDir }}">
</form>

<!-- KPI Cards -->
<div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
    <div class="card p-4 text-center">
        <div class="text-xs text-slate-400 mb-1">Total Revenue</div>
        <div class="text-2xl font-bold text-white">${{ number_format($totalRevenue) }}</div>
        <div class="text-xs text-slate-500 mt-1">{{ $rows->count() }} jobs</div>
    </div>
    <div class="card p-4 text-center">
        <div class="text-xs text-slate-400 mb-1">Total Costs</div>
        <div class="text-2xl font-bold text-orange-400">${{ number_format($totalCosts) }}</div>
        <div class="text-xs text-slate-500 mt-1">Mat ${{ number_format($totalMaterials) }} + Lab ${{ number_format($totalLabour) }}</div>
    </div>
    <div class="card p-4 text-center border {{ $totalProfit >= 0 ? 'border-green-700 bg-green-900/10' : 'border-red-700 bg-red-900/10' }}">
        <div class="text-xs text-slate-400 mb-1">Total Gross Profit</div>
        <div class="text-2xl font-bold {{ $totalProfit >= 0 ? 'text-green-400' : 'text-red-400' }}">${{ number_format($totalProfit) }}</div>
        <div class="text-xs text-slate-500 mt-1">{{ $profitableJobs }} profitable / {{ $unprofitableJobs }} at loss</div>
    </div>
    <div class="card p-4 text-center">
        <div class="text-xs text-slate-400 mb-1">Avg Gross Margin</div>
        <div class="text-2xl font-bold {{ $avgMargin >= 30 ? 'text-green-400' : ($avgMargin >= 15 ? 'text-yellow-400' : 'text-red-400') }}">{{ number_format($avgMargin, 1) }}%</div>
        <div class="text-xs text-slate-500 mt-1">across jobs with revenue</div>
    </div>
</div>

<!-- Margin distribution bar -->
<!-- @if($rows->count() > 0)
@php $total = max(1, $rows->count()); @endphp
<div class="card p-4 mb-6">
    <div class="flex justify-between text-xs text-slate-400 mb-2">
        <span>Margin distribution across {{ $rows->count() }} jobs</span>
        <div class="flex gap-4">
            <span class="flex items-center gap-1"><span class="w-2 h-2 rounded-full bg-red-500 inline-block"></span>Loss</span>
            <span class="flex items-center gap-1"><span class="w-2 h-2 rounded-full bg-orange-400 inline-block"></span>&lt;15%</span>
            <span class="flex items-center gap-1"><span class="w-2 h-2 rounded-full bg-yellow-400 inline-block"></span>15–30%</span>
            <span class="flex items-center gap-1"><span class="w-2 h-2 rounded-full bg-green-500 inline-block"></span>&gt;30%</span>
        </div>
    </div>
    <div class="w-full h-4 bg-slate-800 rounded-full overflow-hidden flex">
        @if($marginBuckets['loss'] > 0)
        <div class="h-full bg-red-500" style="width:{{ round($marginBuckets['loss']/$total*100) }}%" title="{{ $marginBuckets['loss'] }} jobs at a loss"></div>
        @endif
        @if($marginBuckets['low'] > 0)
        <div class="h-full bg-orange-400" style="width:{{ round($marginBuckets['low']/$total*100) }}%" title="{{ $marginBuckets['low'] }} jobs 0–15% margin"></div>
        @endif
        @if($marginBuckets['ok'] > 0)
        <div class="h-full bg-yellow-400" style="width:{{ round($marginBuckets['ok']/$total*100) }}%" title="{{ $marginBuckets['ok'] }} jobs 15–30% margin"></div>
        @endif
        @if($marginBuckets['healthy'] > 0)
        <div class="h-full bg-green-500" style="width:{{ round($marginBuckets['healthy']/$total*100) }}%" title="{{ $marginBuckets['healthy'] }} jobs >30% margin"></div>
        @endif
    </div>
    <div class="flex gap-6 mt-2 text-xs text-slate-400">
        <span>Loss: <strong class="text-red-400">{{ $marginBuckets['loss'] }}</strong></span>
        <span>Low (0–15%): <strong class="text-orange-400">{{ $marginBuckets['low'] }}</strong></span>
        <span>OK (15–30%): <strong class="text-yellow-400">{{ $marginBuckets['ok'] }}</strong></span>
        <span>Healthy (&gt;30%): <strong class="text-green-400">{{ $marginBuckets['healthy'] }}</strong></span>
    </div>
</div>
@endif -->

<!-- Sort helpers -->
@php
function gpSortUrl(string $col, string $currentSort, string $currentDir, array $params): string {
    $dir = ($currentSort === $col && $currentDir === 'desc') ? 'asc' : 'desc';
    return route('reports.gross-profit', array_merge($params, ['sort_by' => $col, 'sort_dir' => $dir]));
}
$filterParams = array_filter([
    'from' => request('from'), 'to' => request('to'),
    'pm_filter' => request('pm_filter'), 'stage_filter' => request('stage_filter'), 'job_number' => request('job_number'),
]);
@endphp

<!-- Jobs Table -->
<div class="card overflow-hidden">
    <div class="p-4 border-b border-slate-700 flex items-center justify-between">
        <h3 class="flex items-center gap-2"><i class="fas fa-chart-line text-green-400 text-sm"></i>Job Profitability</h3>
        <span class="text-xs text-slate-500">Click column headers to sort</span>
    </div>

    @if($rows->count() > 0)
    <div class="overflow-x-auto">
        <table class="w-full text-sm">
            <thead>
                <tr class="text-xs text-slate-400 uppercase border-b border-slate-700">
                    <th class="px-4 py-3 text-left">
                        <a href="{{ gpSortUrl('job_number', $sortBy, $sortDir, $filterParams) }}"
                           class="hover:text-white flex items-center gap-1">
                            Job # @if($sortBy==='job_number')<i class="fas fa-sort-{{ $sortDir==='asc'?'up':'down' }} text-blue-400"></i>@endif
                        </a>
                    </th>
                    <th class="px-4 py-3 text-left">Client / PM</th>
                    <th class="px-4 py-3 text-left">Stage</th>
                    <!-- <th class="px-4 py-3 text-right">
                        <a href="{{ gpSortUrl('revenue', $sortBy, $sortDir, $filterParams) }}"
                           class="hover:text-white flex items-center justify-end gap-1">
                            Revenue @if($sortBy==='revenue')<i class="fas fa-sort-{{ $sortDir==='asc'?'up':'down' }} text-blue-400"></i>@endif
                        </a>
                    </th>
                    <th class="px-4 py-3 text-right">
                        <a href="{{ gpSortUrl('material_cost', $sortBy, $sortDir, $filterParams) }}"
                           class="hover:text-white flex items-center justify-end gap-1">
                            Materials @if($sortBy==='material_cost')<i class="fas fa-sort-{{ $sortDir==='asc'?'up':'down' }} text-blue-400"></i>@endif
                        </a>
                    </th>
                    <th class="px-4 py-3 text-right">
                        <a href="{{ gpSortUrl('labour_cost', $sortBy, $sortDir, $filterParams) }}"
                           class="hover:text-white flex items-center justify-end gap-1">
                            Labour @if($sortBy==='labour_cost')<i class="fas fa-sort-{{ $sortDir==='asc'?'up':'down' }} text-blue-400"></i>@endif
                        </a>
                    </th>
                    <th class="px-4 py-3 text-right">
                        <a href="{{ gpSortUrl('gross_profit', $sortBy, $sortDir, $filterParams) }}"
                           class="hover:text-white flex items-center justify-end gap-1">
                            Gross Profit @if($sortBy==='gross_profit')<i class="fas fa-sort-{{ $sortDir==='asc'?'up':'down' }} text-blue-400"></i>@endif
                        </a>
                    </th>
                    <th class="px-4 py-3 text-right">
                        <a href="{{ gpSortUrl('gross_margin', $sortBy, $sortDir, $filterParams) }}"
                           class="hover:text-white flex items-center justify-end gap-1">
                            Margin % @if($sortBy==='gross_margin')<i class="fas fa-sort-{{ $sortDir==='asc'?'up':'down' }} text-blue-400"></i>@endif
                        </a>
                    </th> -->
                    <!-- <th class="px-4 py-3 text-center">Bar</th> -->
                    <th class="px-4 py-3 text-center">Detail</th>
                </tr>
            </thead>
            <tbody>
                @foreach($rows as $row)
                @php
                $gpColor = $row['gross_profit'] >= 0 ? 'text-green-400' : 'text-red-400';
                $barColor = $row['gross_margin'] < 0 ? 'bg-red-500' : ($row['gross_margin'] < 15 ? 'bg-orange-400' : ($row['gross_margin'] < 30 ? 'bg-yellow-400' : 'bg-green-500'));
                $barWidth = min(100, max(0, abs($row['gross_margin'])));
                @endphp
                <tr class="table-row border-b border-slate-800 hover:bg-slate-800/40">
                    <td class="px-4 py-3 font-mono text-blue-300 text-xs">{{ $row['job_number'] }}</td>
                    <td class="px-4 py-3">
                        <div class="text-sm text-white font-medium">{{ $row['client'] }}</div>
                        <div class="text-xs text-slate-500">{{ $row['pm'] }} · {{ $row['created_at'] }}</div>
                    </td>
                    <td class="px-4 py-3">
                        <span class="badge badge-blue text-xs">{{ ucfirst($row['stage']) }}</span>
                    </td>
                    <!-- <td class="px-4 py-3 text-right text-white font-medium">${{ number_format($row['revenue']) }}</td>
                    <td class="px-4 py-3 text-right text-orange-400">${{ number_format($row['material_cost']) }}</td>
                    <td class="px-4 py-3 text-right text-blue-400">${{ number_format($row['labour_cost']) }}</td>
                    <td class="px-4 py-3 text-right font-bold {{ $gpColor }}">${{ number_format($row['gross_profit']) }}</td>
                    <td class="px-4 py-3 text-right font-bold {{ $gpColor }}">{{ $row['gross_margin'] }}%</td> -->
                    <!-- <td class="px-4 py-3 w-24">
                        <div class="w-full h-2 bg-slate-700 rounded-full overflow-hidden">
                            <div class="h-full {{ $barColor }} rounded-full" style="width:{{ $barWidth }}%"></div>
                        </div>
                    </td> -->
                    <td class="px-4 py-3 text-center">
                        <a href="{{ route('reports.gross-profit.show', $row['id']) }}" class="text-blue-400 hover:text-blue-300 text-xs" title="Detailed GP Report">
                            <i class="fas fa-chart-bar"></i>
                        </a>
                        &nbsp;
                        <a href="{{ route('reports.gross-profit.pdf', $row['id']) }}" class="text-purple-400 hover:text-purple-300 text-xs" title="Export PDF">
                            <i class="fas fa-file-pdf"></i>
                        </a>
                    </td>
                </tr>
                @endforeach
            </tbody>
            <!-- Totals row -->
            <!-- <tfoot>
                <tr class="bg-slate-800/50 border-t-2 border-slate-600 text-sm font-semibold">
                    <td class="px-4 py-3 text-slate-300" colspan="3">{{ $rows->count() }} jobs total</td>
                    <td class="px-4 py-3 text-right text-white">${{ number_format($totalRevenue) }}</td>
                    <td class="px-4 py-3 text-right text-orange-400">${{ number_format($totalMaterials) }}</td>
                    <td class="px-4 py-3 text-right text-blue-400">${{ number_format($totalLabour) }}</td>
                    <td class="px-4 py-3 text-right {{ $totalProfit >= 0 ? 'text-green-400' : 'text-red-400' }}">${{ number_format($totalProfit) }}</td>
                    <td class="px-4 py-3 text-right {{ $avgMargin >= 30 ? 'text-green-400' : ($avgMargin >= 15 ? 'text-yellow-400' : 'text-red-400') }}">{{ number_format($avgMargin, 1) }}%</td>
                    <td colspan="2"></td>
                </tr>
            </tfoot> -->
        </table>
    </div>
    @else
    <div class="p-12 text-center">
        <i class="fas fa-chart-line text-slate-700 text-4xl mb-3 block"></i>
        <p class="text-slate-400">No jobs found for the selected filters.</p>
        <a href="{{ route('reports.gross-profit') }}" class="text-blue-400 text-sm hover:text-blue-300 mt-1 inline-block">Clear filters</a>
    </div>
    @endif
</div>

@endsection
