@extends('layouts.dashboard.superadminapp')

@section('title', 'Customer/Vendor Report')

@section('styles')
<style>
    div.dt-buttons {
        float: left;
        display: flex !important;
    }
    .dataTable {
        overflow-x: auto !important;
        display: table !important;
    }
    .dt-buttons .btn {
        margin-right: 0.5rem !important;
        padding: 0.25rem 0.75rem !important;
        font-size: 0.95rem !important;
    }
    .stat-card {
        border-radius: 10px;
        padding: 20px;
        text-align: center;
        color: #fff;
        transition: transform 0.2s;
    }
    .stat-card:hover {
        transform: translateY(-3px);
    }
    .stat-card .stat-value {
        font-size: 1.8rem;
        font-weight: bold;
    }
    .stat-card .stat-label {
        font-size: 0.85rem;
        opacity: 0.9;
    }
    .bg-total { background: linear-gradient(135deg, #4e73df 0%, #224abe 100%); }
    .bg-customer { background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%); }
    .bg-vendor { background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%); }
    .bg-active { background: linear-gradient(135deg, #36b9cc 0%, #258391 100%); }
    .bg-inactive { background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%); }
</style>
@endsection

@section('content')

<!-- Page Heading -->
<x-layout.page-header title="UEPL | Customer/Vendor Report" icon="chart-bar" iconColor="info" />

<!-- Alerts -->
@if(session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif
@if(session('error'))
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle mr-2"></i>{{ session('error') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif

<!-- Filter Card -->
<div class="card shadow mb-4">
    <div class="card-header py-3" style="background: linear-gradient(135deg, #6c757d 0%, #495057 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-filter mr-2"></i> Filter Options
        </h6>
    </div>
    <div class="card-body">
        <form id="customerReportFilters" method="POST" action="{{ route('superadmin.report.customerreport') }}">
            @csrf
            <div class="row align-items-end">
                <div class="col-md-2 mb-3">
                    <label class="small font-weight-bold">Role Type</label>
                    <select name="company_role" id="company_role" class="form-control">
                        <option value="">All Roles</option>
                        <option value="customer" {{ request('company_role') == 'customer' ? 'selected' : '' }}>Customer</option>
                        <option value="vendor" {{ request('company_role') == 'vendor' ? 'selected' : '' }}>Vendor</option>
                    </select>
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Company Name</label>
                    <select name="company" id="company" class="form-control">
                        <option value="">All Companies</option>
                        @foreach($companyNames as $name)
                            <option value="{{ $name }}" {{ request('company') == $name ? 'selected' : '' }}>{{ $name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2 mb-3">
                    <label class="small font-weight-bold">From Date</label>
                    <input type="date" name="from_date" id="from_date" class="form-control" value="{{ request('from_date') }}">
                </div>
                <div class="col-md-2 mb-3">
                    <label class="small font-weight-bold">To Date</label>
                    <input type="date" name="to_date" id="to_date" class="form-control" value="{{ request('to_date') }}">
                </div>
                <div class="col-md-3 mb-3">
                    <button type="submit" class="btn btn-primary btn-sm mr-2">
                        <i class="fas fa-search mr-1"></i> Apply Filter
                    </button>
                    <a href="{{ route('superadmin.report.customerreport') }}" class="btn btn-secondary btn-sm mr-2">
                        <i class="fas fa-redo mr-1"></i> Reset
                    </a>
                    <button type="button" class="btn btn-success btn-sm" id="exportExcelBtn">
                        <i class="fas fa-file-excel mr-1"></i> Export
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

@php
    $totalRecords = $customers->count();
    $totalCustomers = $customers->where('company_role', 'customer')->count();
    $totalVendors = $customers->where('company_role', 'vendor')->count();
    $activeCount = $customers->filter(fn($c) => $c->status == 1 || strtolower($c->status) == 'active')->count();
    $inactiveCount = $totalRecords - $activeCount;
@endphp

<!-- Summary Statistics -->
<div class="row mb-4">
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="stat-card bg-total">
            <div class="stat-value">{{ $totalRecords }}</div>
            <div class="stat-label"><i class="fas fa-building mr-1"></i> Total Records</div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="stat-card bg-customer">
            <div class="stat-value">{{ $totalCustomers }}</div>
            <div class="stat-label"><i class="fas fa-users mr-1"></i> Customers</div>
        </div>
    </div>
    <div class="col-xl-2 col-md-4 mb-3">
        <div class="stat-card bg-vendor">
            <div class="stat-value">{{ $totalVendors }}</div>
            <div class="stat-label"><i class="fas fa-truck mr-1"></i> Vendors</div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card bg-active">
            <div class="stat-value">{{ $activeCount }}</div>
            <div class="stat-label"><i class="fas fa-check-circle mr-1"></i> Active</div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card bg-inactive">
            <div class="stat-value">{{ $inactiveCount }}</div>
            <div class="stat-label"><i class="fas fa-times-circle mr-1"></i> Inactive</div>
        </div>
    </div>
</div>

<!-- Customer/Vendor Report Table -->
<div class="card shadow mb-4">
    <div class="card-header py-3" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-address-book mr-2"></i> Customer/Vendor Directory
        </h6>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table id="customerTable" class="table table-bordered table-striped table-sm" width="100%">
                <thead class="thead-light">
                    <tr class="text-center">
                        <th>#</th>
                        <th>Role</th>
                        <th>Company Name</th>
                        <th>Email</th>
                        <th>Mobile</th>
                        <th>GST No</th>
                        <th>Company Type</th>
                        <th>Billing Address</th>
                        <th>Contact Persons</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($customers as $index => $customer)
                        <tr class="text-center">
                            <td>{{ $index + 1 }}</td>
                            <td>
                                @if(strtolower($customer->company_role) == 'customer')
                                    <span class="badge badge-success"><i class="fas fa-users mr-1"></i>Customer</span>
                                @else
                                    <span class="badge badge-warning"><i class="fas fa-truck mr-1"></i>Vendor</span>
                                @endif
                            </td>
                            <td class="text-left font-weight-bold">
                                {{ $customer->company }}
                                @if($customer->company_nickname)
                                    <br><small class="text-muted">({{ $customer->company_nickname }})</small>
                                @endif
                            </td>
                            <td class="text-left">
                                @if($customer->email)
                                    <span class="text-primary">{{ $customer->email }}</span>
                                @else
                                    <span class="text-muted">-</span>
                                @endif
                            </td>
                            <td>
                                @if($customer->mobile)
                                    <span class="font-weight-bold">{{ $customer->mobile }}</span>
                                @else
                                    <span class="text-muted">-</span>
                                @endif
                            </td>
                            <td>{{ $customer->gstno ?? '-' }}</td>
                            <td>{{ $customer->company_type ?? '-' }}</td>
                            <td class="text-left" style="max-width: 200px;">
                                {{ Str::limit($customer->billing_address, 50) ?? '-' }}
                            </td>
                            <td>
                                @if($customer->contactPersons->count() > 0)
                                    <span class="badge badge-info" title="{{ $customer->contactPersons->pluck('name')->join(', ') }}">
                                        {{ $customer->contactPersons->count() }} person(s)
                                    </span>
                                @else
                                    <span class="text-muted">-</span>
                                @endif
                            </td>
                            <td>
                                @if($customer->status == 1 || strtolower($customer->status) == 'active')
                                    <span class="badge badge-success">Active</span>
                                @else
                                    <span class="badge badge-danger">Inactive</span>
                                @endif
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="10" class="text-center text-muted py-4">
                                <i class="fas fa-inbox fa-2x mb-2 d-block"></i>
                                No customer/vendor records found. Please adjust filters and try again.
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Quick Summary Cards -->
<div class="row">
    <div class="col-md-6">
        <div class="card shadow mb-4">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-users mr-2"></i> Top Customers
                </h6>
            </div>
            <div class="card-body p-0">
                <table class="table table-sm mb-0">
                    <thead class="thead-light">
                        <tr>
                            <th>Company</th>
                            <th>Contact</th>
                            <th>Mobile</th>
                        </tr>
                    </thead>
                    <tbody>
                        @php
                            $topCustomers = $customers->where('company_role', 'customer')->take(5);
                        @endphp
                        @forelse($topCustomers as $customer)
                            <tr>
                                <td class="font-weight-bold">{{ Str::limit($customer->company, 25) }}</td>
                                <td>{{ $customer->contactPersons->first()->name ?? '-' }}</td>
                                <td>{{ $customer->mobile ?? '-' }}</td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="3" class="text-center text-muted">No customers found</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card shadow mb-4">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-truck mr-2"></i> Top Vendors
                </h6>
            </div>
            <div class="card-body p-0">
                <table class="table table-sm mb-0">
                    <thead class="thead-light">
                        <tr>
                            <th>Company</th>
                            <th>Contact</th>
                            <th>Mobile</th>
                        </tr>
                    </thead>
                    <tbody>
                        @php
                            $topVendors = $customers->where('company_role', 'vendor')->take(5);
                        @endphp
                        @forelse($topVendors as $vendor)
                            <tr>
                                <td class="font-weight-bold">{{ Str::limit($vendor->company, 25) }}</td>
                                <td>{{ $vendor->contactPersons->first()->name ?? '-' }}</td>
                                <td>{{ $vendor->mobile ?? '-' }}</td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="3" class="text-center text-muted">No vendors found</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script>
$(document).ready(function() {
    $('#customerTable').DataTable({
        dom: 'Bfrtip',
        buttons: [
            { extend: 'copy', className: 'btn btn-secondary btn-sm' },
            { extend: 'csv', className: 'btn btn-secondary btn-sm' },
            { extend: 'excel', className: 'btn btn-secondary btn-sm' },
            { extend: 'pdf', className: 'btn btn-secondary btn-sm' },
            { extend: 'print', className: 'btn btn-secondary btn-sm' },
            { extend: 'colvis', className: 'btn btn-secondary btn-sm' }
        ],
        pageLength: 25,
        responsive: true,
        order: [[2, 'asc']], // Sort by company name
        language: {
            emptyTable: "No customer/vendor records found"
        }
    });

    // Export Excel logic
    $('#exportExcelBtn').click(function() {
        let form = $('#customerReportFilters');
        let originalAction = form.attr('action');
        form.attr('action', '{{ route('superadmin.report.customerreport.export') }}');
        form.attr('target', '_blank');
        form.submit();
        setTimeout(function() {
            form.attr('action', originalAction);
            form.removeAttr('target');
        }, 100);
    });
});
</script>
@endsection
