@extends('layouts.app')

@push('style')
<style>
    .small-box {
        border-radius: 10px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        transition: transform 0.2s ease;
    }
    .small-box:hover {
        transform: translateY(-2px);
    }
    .card {
        border-radius: 10px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
    .card-outline {
        border-top: 3px solid;
    }
    .chart-container {
        position: relative;
        height: 250px;
    }
    .table-responsive {
        border-radius: 8px;
    }
    .badge {
        font-size: 0.9em;
    }
</style>
@endpush

@section('main')
    <!-- Content Header -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0"><i class="fas fa-chart-bar"></i> Sales Management Dashboard</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Home</a></li>
                        <li class="breadcrumb-item active">Sales Management</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <!-- Quick Stats Row -->
            <div class="row">
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-info">
                        <div class="inner">
                            <h3>{{ $totalSales }}</h3>
                            <p>Total Sales Today</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-shopping-cart"></i>
                        </div>
                        <a href="{{ route('sales.history') }}" class="small-box-footer">
                            View All <i class="fas fa-arrow-circle-right"></i>
                        </a>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-success">
                        <div class="inner">
                            <h3>{{ $all_settings->currency ?? 'BDT' }} {{ number_format($todayRevenue, 2) }}</h3>
                            <p>Today's Revenue</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-money-bill-wave"></i>
                        </div>
                        <a href="{{ route('sales.profit.report') }}" class="small-box-footer">
                            View Report <i class="fas fa-arrow-circle-right"></i>
                        </a>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-warning">
                        <div class="inner">
                            <h3>{{ $all_settings->currency ?? 'BDT' }} {{ number_format($pendingPayments, 2) }}</h3>
                            <p>Direct Sales Today</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-shopping-bag"></i>
                        </div>
                        <a href="{{ route('direct-sales.index') }}" class="small-box-footer">
                            View Details <i class="fas fa-arrow-circle-right"></i>
                        </a>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-danger">
                        <div class="inner">
                            <h3>{{ $all_settings->currency ?? 'BDT' }} {{ number_format($todayProfit, 2) }}</h3>
                            <p>Today's Profit</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-chart-line"></i>
                        </div>
                        <a href="{{ route('sales.profit.report') }}" class="small-box-footer">
                            View Profit Report <i class="fas fa-arrow-circle-right"></i>
                        </a>
                    </div>
                </div>
            </div>

            <!-- Action Cards -->
            <div class="row">
                <div class="col-md-3">
                    <div class="card card-primary card-outline">
                        <div class="card-body box-profile">
                            <div class="text-center">
                                <i class="fas fa-plus-circle fa-3x text-primary mb-2"></i>
                            </div>
                            <h3 class="profile-username text-center">New Sale</h3>
                            <p class="text-muted text-center">Create a new sale transaction</p>
                            <a href="{{ route('sales.create') }}" class="btn btn-primary btn-block">
                                <i class="fas fa-plus"></i> Create Sale
                            </a>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card card-success card-outline">
                        <div class="card-body box-profile">
                            <div class="text-center">
                                <i class="fas fa-history fa-3x text-success mb-2"></i>
                            </div>
                            <h3 class="profile-username text-center">Sales History</h3>
                            <p class="text-muted text-center">View all sales transactions</p>
                            <a href="{{ route('sales.history') }}" class="btn btn-success btn-block">
                                <i class="fas fa-list"></i> View History
                            </a>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card card-info card-outline">
                        <div class="card-body box-profile">
                            <div class="text-center">
                                <i class="fas fa-chart-bar fa-3x text-info mb-2"></i>
                            </div>
                            <h3 class="profile-username text-center">Profit Reports</h3>
                            <p class="text-muted text-center">Analyze sales performance</p>
                            <a href="{{ route('report.index') }}" class="btn btn-info btn-block">
                                <i class="fas fa-chart-line"></i> View Reports
                            </a>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card card-warning card-outline">
                        <div class="card-body box-profile">
                            <div class="text-center">
                                <i class="fas fa-exchange-alt fa-3x text-warning mb-2"></i>
                            </div>
                            <h3 class="profile-username text-center">Direct Sales</h3>
                            <p class="text-muted text-center">Quick sale transactions</p>
                            <a href="{{ route('direct-sales.index') }}" class="btn btn-warning btn-block">
                                <i class="fas fa-shopping-bag"></i> Direct Sales
                            </a>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Recent Sales Table -->
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-clock mr-1"></i>
                                Recent Sales (Last 10)
                            </h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                    <i class="fas fa-minus"></i>
                                </button>
                                <a href="{{ route('sales.history') }}" class="btn btn-tool">
                                    <i class="fas fa-external-link-alt"></i>
                                </a>
                            </div>
                        </div>
                        <div class="card-body table-responsive p-0">
                            <table class="table table-striped table-valign-middle">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Type</th>
                                        <th>Date</th>
                                        <th>Customer</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @forelse($recentSales as $sale)
                                        <tr>
                                            <td>
                                                @if($sale->type === 'direct_sale')
                                                    <span class="badge badge-success">DS-{{ $sale->original_model->id }}</span>
                                                @else
                                                    <span class="badge badge-info">#{{ $sale->id }}</span>
                                                @endif
                                            </td>
                                            <td>
                                                @if($sale->type === 'direct_sale')
                                                    <span class="badge badge-primary">
                                                        <i class="fas fa-shopping-cart"></i> Direct Sale
                                                    </span>
                                                @else
                                                    <span class="badge badge-secondary">
                                                        <i class="fas fa-store"></i> Regular Sale
                                                    </span>
                                                @endif
                                            </td>
                                            <td>
                                                {{ $sale->created_at->format('M d, Y') }}<br>
                                                <small class="text-muted">{{ $sale->created_at->format('h:i A') }}</small>
                                            </td>
                                            <td>
                                                @if($sale->customer)
                                                    <strong>{{ $sale->customer->name }}</strong><br>
                                                    <small class="text-muted">{{ $sale->customer->phone ?? 'N/A' }}</small>
                                                @elseif($sale->type === 'direct_sale' && $sale->customer_name)
                                                    <strong>{{ $sale->customer_name }}</strong><br>
                                                    <small class="text-muted">Direct Sale</small>
                                                @else
                                                    <span class="text-muted">Walk-in Customer</span>
                                                @endif
                                            </td>
                                            <td>
                                                <strong>{{ $all_settings->currency ?? 'BDT' }} {{ number_format($sale->total_amount, 2) }}</strong>
                                                @if($sale->due_amount > 0)
                                                    <br><small class="text-danger">Due: {{ $all_settings->currency ?? 'BDT' }} {{ number_format($sale->due_amount, 2) }}</small>
                                                @endif
                                            </td>
                                            <td>
                                                @if ($sale->payment_status == 'paid')
                                                    <span class="badge badge-success">Paid</span>
                                                @elseif($sale->payment_status == 'unpaid')
                                                    <span class="badge badge-danger">Unpaid</span>
                                                @else
                                                    <span class="badge badge-warning">Partial</span>
                                                @endif
                                            </td>
                                            <td>
                                                <div class="btn-group" role="group">
                                                    @if($sale->type === 'direct_sale')
                                                        <a href="{{ route('sales.table.invoice.public', $sale->id) }}" target="_blank"
                                                           class="btn btn-sm btn-primary" title="Print Receipt">
                                                            <i class="fas fa-print"></i>
                                                        </a>
                                                    @else
                                                        <a href="{{ route('sales.table.invoice.public', $sale->id) }}" target="_blank"
                                                           class="btn btn-sm btn-primary" title="Print Receipt">
                                                            <i class="fas fa-print"></i>
                                                        </a>
                                                        @if($sale->payment_status != 'paid')
                                                            <a href="{{ route('sales.edit', $sale->id) }}"
                                                               class="btn btn-sm btn-warning" title="Edit">
                                                                <i class="fas fa-edit"></i>
                                                            </a>
                                                        @endif
                                                    @endif
                                                    
                                                    @if($sale->customer && $sale->customer->phone)
                                                        <button type="button" class="btn btn-sm btn-success whatsapp-send-btn" 
                                                                title="Send WhatsApp" 
                                                                data-sale-id="{{ $sale->id }}" 
                                                                data-customer-phone="{{ $sale->customer->phone }}"
                                                                data-customer-name="{{ $sale->customer->name }}">
                                                            <i class="fab fa-whatsapp"></i>
                                                        </button>
                                                    @elseif($sale->type === 'direct_sale' && $sale->customer_phone)
                                                        <button type="button" class="btn btn-sm btn-success whatsapp-send-btn" 
                                                                title="Send WhatsApp" 
                                                                data-sale-id="{{ $sale->id }}" 
                                                                data-customer-phone="{{ $sale->customer_phone }}"
                                                                data-customer-name="{{ $sale->customer_name ?? 'Customer' }}">
                                                            <i class="fab fa-whatsapp"></i>
                                                        </button>
                                                    @endif
                                                </div>
                                            </td>
                                        </tr>
                                    @empty
                                        <tr>
                                            <td colspan="7" class="text-center text-muted py-4">
                                                <i class="fas fa-inbox fa-2x mb-2"></i><br>
                                                No sales found for today
                                            </td>
                                        </tr>
                                    @endforelse
                                </tbody>
                            </table>
                        </div>
                        <div class="card-footer clearfix">
                            <a href="{{ route('sales.history') }}" class="btn btn-sm btn-info float-right">
                                View All Sales <i class="fas fa-arrow-circle-right"></i>
                            </a>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Sales Statistics -->
            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-chart-pie mr-1"></i>
                                Payment Status Distribution
                            </h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                    <i class="fas fa-minus"></i>
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="chart-container">
                                <canvas id="paymentStatusChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-chart-line mr-1"></i>
                                Weekly Sales Trend
                            </h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                    <i class="fas fa-minus"></i>
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="chart-container">
                                <canvas id="salesTrendChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
@endsection

@push('script')
<script src="{{ asset('assets/plugins/chart.js/Chart.min.js') }}"></script>
<script>
    $(document).ready(function() {
        // Payment Status Chart
        var ctx1 = document.getElementById('paymentStatusChart').getContext('2d');
        var paymentStatusChart = new Chart(ctx1, {
            type: 'doughnut',
            data: {
                labels: ['Paid', 'Unpaid', 'Partial'],
                datasets: [{
                    data: [{{ $paidCount ?? 0 }}, {{ $unpaidCount ?? 0 }}, {{ $partialCount ?? 0 }}],
                    backgroundColor: ['#28a745', '#dc3545', '#ffc107'],
                    borderWidth: 2,
                    borderColor: '#fff'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                legend: {
                    position: 'bottom',
                },
                tooltips: {
                    callbacks: {
                        label: function(tooltipItem, data) {
                            var dataset = data.datasets[tooltipItem.datasetIndex];
                            var currentValue = dataset.data[tooltipItem.index];
                            return data.labels[tooltipItem.index] + ': ' + currentValue;
                        }
                    }
                }
            }
        });

        // Sales Trend Chart
        var ctx2 = document.getElementById('salesTrendChart').getContext('2d');
        var salesTrendChart = new Chart(ctx2, {
            type: 'line',
            data: {
                labels: {!! json_encode($weeklyLabels ?? []) !!},
                datasets: [{
                    label: 'Sales Amount ({{ $all_settings->currency ?? 'BDT' }})',
                    data: {!! json_encode($weeklyData ?? []) !!},
                    borderColor: '#007bff',
                    backgroundColor: 'rgba(0, 123, 255, 0.1)',
                    tension: 0.4,
                    fill: true,
                    borderWidth: 2,
                    pointBackgroundColor: '#007bff',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true,
                            callback: function(value) {
                                return '{{ $all_settings->currency ?? 'BDT' }} ' + value.toFixed(2);
                            }
                        }
                    }]
                },
                legend: {
                    display: false
                },
                tooltips: {
                    callbacks: {
                        label: function(tooltipItem) {
                            return 'Sales: {{ $all_settings->currency ?? 'BDT' }} ' + tooltipItem.yLabel.toFixed(2);
                        }
                    }
                }
            }
        });
    });

    // WhatsApp functionality
    $(document).on('click', '.whatsapp-send-btn', function() {
        var button = $(this);
        var saleId = button.data('sale-id');
        var customerPhone = button.data('customer-phone');
        var customerName = button.data('customer-name');
        
        // Disable button and show loading
        button.prop('disabled', true);
        var originalHtml = button.html();
        button.html('<i class="fas fa-spinner fa-spin"></i>');
        
        // Send WhatsApp message
        $.ajax({
            url: '{{ route("whatsapp.send.invoice") }}',
            method: 'POST',
            data: {
                _token: '{{ csrf_token() }}',
                id: saleId,
                phone: customerPhone,
                type: 'sale',
                get_url_only: true
            },
            success: function(response) {
                if (response.success) {
                    // Open WhatsApp in new tab/window
                    if (response.whatsapp_url) {
                        window.open(response.whatsapp_url, '_blank');
                    }
                    
                    // Show success message
                    toastr.success('WhatsApp message ready! Opening WhatsApp...', 'Success');
                } else {
                    toastr.error(response.message || 'Failed to generate WhatsApp message', 'Error');
                }
            },
            error: function(xhr, status, error) {
                console.error('WhatsApp send error:', xhr.responseText);
                var errorMessage = 'Failed to send WhatsApp message';
                
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMessage = xhr.responseJSON.message;
                }
                
                toastr.error(errorMessage, 'Error');
            },
            complete: function() {
                // Re-enable button and restore original text
                button.prop('disabled', false);
                button.html(originalHtml);
            }
        });
    });
</script>
@endpush