@extends('layouts.dashboard.superadminapp')

@section('title', 'Account Dashboard')

@section('styles')
<style>
    /* Compact Dashboard Styles */
    .dashboard-card {
        border: none;
        border-radius: 8px;
        transition: all 0.2s ease;
        overflow: hidden;
        cursor: pointer;
        text-decoration: none;
        display: block;
    }
    .dashboard-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12) !important;
        text-decoration: none;
    }

    /* Compact KPI Cards */
    .kpi-card {
        border-radius: 8px;
        color: #fff;
        position: relative;
        overflow: hidden;
        padding: 0.75rem 1rem !important;
    }
    .kpi-card .kpi-icon {
        font-size: 2rem;
        opacity: 0.25;
        position: absolute;
        right: 0.75rem;
        top: 50%;
        transform: translateY(-50%);
    }
    .kpi-card .kpi-value {
        font-size: 1.5rem;
        font-weight: 700;
        margin-bottom: 0.1rem;
        line-height: 1.2;
    }
    .kpi-card .kpi-label {
        font-size: 0.7rem;
        text-transform: uppercase;
        letter-spacing: 0.3px;
        opacity: 0.9;
    }
    .kpi-card .kpi-growth {
        display: inline-block;
        padding: 0.1rem 0.4rem;
        border-radius: 4px;
        font-size: 0.6rem;
        font-weight: 600;
        margin-top: 0.25rem;
        background: rgba(255,255,255,0.2);
    }

    /* Gradient backgrounds */
    .bg-gradient-success { background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%); }
    .bg-gradient-primary { background: linear-gradient(135deg, #4e73df 0%, #224abe 100%); }
    .bg-gradient-warning { background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%); }
    .bg-gradient-info { background: linear-gradient(135deg, #36b9cc 0%, #258391 100%); }
    .bg-gradient-danger { background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%); }

    /* Compact Cards */
    .compact-card {
        border: none;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    }
    .compact-card .card-header {
        background: transparent;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        padding: 0.5rem 0.75rem;
    }
    .compact-card .card-body {
        padding: 0.5rem 0.75rem;
    }
    .compact-card .card-header h6 {
        font-size: 0.8rem;
        margin: 0;
    }

    /* Compact Chart Cards */
    .chart-card {
        border: none;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    }
    .chart-card .card-header {
        background: transparent;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        padding: 0.5rem 0.75rem;
    }
    .chart-card .card-body {
        padding: 0.5rem 0.75rem;
    }

    /* Compact Quick Links */
    .quick-link-card {
        background: #fff;
        border-radius: 8px;
        padding: 0.75rem;
        text-align: center;
        transition: all 0.2s;
        border: 1px solid rgba(0, 0, 0, 0.05);
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
    }
    .quick-link-card:hover {
        border-color: #4e73df;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(78, 115, 223, 0.15);
    }
    .quick-link-card i {
        font-size: 1.5rem;
        margin-bottom: 0.35rem;
    }
    .quick-link-card .link-title {
        font-weight: 600;
        color: #333;
        font-size: 0.75rem;
    }

    /* Compact Page Header */
    .page-header {
        background: linear-gradient(135deg, #fff 0%, #f8f9fc 100%);
        border-radius: 8px;
        padding: 0.5rem 1rem;
        margin-bottom: 0.75rem;
        box-shadow: 0 1px 5px rgba(0, 0, 0, 0.04);
    }
    .page-header h1 {
        font-size: 1rem;
        font-weight: 600;
        color: #2d3748;
        margin: 0;
    }

    /* DateTime Display */
    .datetime-display {
        gap: 0.5rem;
    }
    .date-box, .time-box {
        display: flex;
        align-items: center;
        gap: 0.35rem;
        background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
        padding: 0.35rem 0.65rem;
        border-radius: 6px;
        border: 1px solid #e2e8f0;
        font-size: 0.75rem;
        color: #475569;
        font-weight: 500;
    }
    .date-box i, .time-box i {
        color: #4e73df;
        font-size: 0.7rem;
    }
    .time-box {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        color: #fff;
        border: none;
        min-width: 85px;
        justify-content: center;
    }
    .time-box i {
        color: rgba(255,255,255,0.8);
    }
    .time-box .display-time {
        font-family: 'Courier New', monospace;
        font-weight: 600;
        letter-spacing: 0.5px;
    }

    /* Compact row margins */
    .row.mb-4 { margin-bottom: 0.75rem !important; }
    .row.mb-3 { margin-bottom: 0.5rem !important; }
    .col-xl-3.mb-3, .col-md-6.mb-3, .col-xl-6.mb-3, .col-lg-4.mb-3, .col-lg-8.mb-3, .col-md-4.mb-3, .col-md-8.mb-3 {
        margin-bottom: 0.5rem !important;
    }

    /* Compact table */
    .table-sm td, .table-sm th {
        padding: 0.3rem 0.5rem;
        font-size: 0.8rem;
    }

    /* Progress Stats */
    .progress {
        height: 6px !important;
        border-radius: 3px;
    }

    /* Summary Item */
    .summary-item {
        padding: 0.5rem 0;
        border-bottom: 1px solid #eee;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .summary-item:last-child {
        border-bottom: none;
    }
    .summary-item .summary-label {
        color: #666;
        font-size: 0.75rem;
    }
    .summary-item .summary-value {
        font-weight: 700;
        color: #333;
        font-size: 0.85rem;
    }

    /* Invoice Status */
    .invoice-status {
        padding: 0.15rem 0.5rem;
        border-radius: 4px;
        font-size: 0.65rem;
        font-weight: 600;
    }
    .invoice-status.pending {
        background: #fff3cd;
        color: #856404;
    }
    .invoice-status.paid {
        background: #d4edda;
        color: #155724;
    }
    .invoice-status.overdue {
        background: #f8d7da;
        color: #721c24;
    }

    /* Filter buttons */
    .filter-btn {
        padding: 0.2rem 0.5rem;
        border-radius: 4px;
        font-size: 0.7rem;
    }

    /* Financial Overview Display */
    .financial-stat {
        text-align: center;
        padding: 0.5rem;
    }
    .financial-stat .stat-value {
        font-size: 1.5rem;
        font-weight: 700;
        line-height: 1;
    }
    .financial-stat .stat-label {
        font-size: 0.7rem;
        color: #6c757d;
        margin-top: 0.25rem;
    }

    /* Responsive adjustments */
    @media (max-width: 768px) {
        .kpi-card .kpi-value { font-size: 1.25rem; }
        .quick-link-card i { font-size: 1.25rem; }
        .financial-stat .stat-value { font-size: 1.25rem; }
    }
</style>
@endsection

@section('content')

<div class="container-fluid">

    <!-- Page Header -->
    <div class="page-header d-flex align-items-center justify-content-between flex-wrap">
        <h1><i class="fas fa-calculator mr-2 text-primary"></i>Account Dashboard</h1>
        <div class="datetime-display d-flex align-items-center">
            <div class="date-box">
                <i class="far fa-calendar-alt"></i>
                <span id="day">{{ now()->format('l') }}</span>,
                <span id="daynum">{{ now()->format('d') }}</span>
                <span id="month">{{ now()->format('F') }}</span>
                <span id="year">{{ now()->format('Y') }}</span>
            </div>
            <div class="time-box">
                <i class="far fa-clock"></i>
                <span class="display-time"></span>
            </div>
        </div>
    </div>

    @php
        $profitMargin = $revenue > 0 ? round(($grossProfit / $revenue) * 100, 1) : 0;
        $expenseRatio = $revenue > 0 ? round(($expenses / $revenue) * 100, 1) : 0;
    @endphp

    <!-- KPI Cards Row -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-3">
            <a href="{{ route('superadmin.invoice.invoicedetails') }}" class="dashboard-card">
                <div class="kpi-card bg-gradient-success shadow">
                    <i class="fas fa-rupee-sign kpi-icon"></i>
                    <div class="kpi-value">{{ number_format($revenue) }}</div>
                    <div class="kpi-label">Revenue</div>
                    <div class="kpi-growth">
                        <i class="fas fa-arrow-up mr-1"></i> {{ $revenueGrowth }} vs last month
                    </div>
                </div>
            </a>
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <a href="{{ route('superadmin.purchase.purchasedetails') }}" class="dashboard-card">
                <div class="kpi-card bg-gradient-danger shadow">
                    <i class="fas fa-file-invoice-dollar kpi-icon"></i>
                    <div class="kpi-value">{{ number_format($expenses) }}</div>
                    <div class="kpi-label">Expenses</div>
                    <div class="kpi-growth">
                        <i class="fas fa-arrow-up mr-1"></i> {{ $expensesGrowth }} vs last month
                    </div>
                </div>
            </a>
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <a href="{{ route('superadmin.invoice.invoicedetails') }}" class="dashboard-card">
                <div class="kpi-card bg-gradient-primary shadow">
                    <i class="fas fa-chart-line kpi-icon"></i>
                    <div class="kpi-value">{{ number_format($grossProfit) }}</div>
                    <div class="kpi-label">Gross Profit</div>
                    <div class="kpi-growth">
                        <i class="fas fa-arrow-up mr-1"></i> {{ $profitGrowth }} vs last month
                    </div>
                </div>
            </a>
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <a href="{{ route('superadmin.routecard.index') }}" class="dashboard-card">
                <div class="kpi-card bg-gradient-warning shadow">
                    <i class="fas fa-cogs kpi-icon"></i>
                    <div class="kpi-value">{{ number_format($productionCost) }}</div>
                    <div class="kpi-label">Production Cost</div>
                    <div class="kpi-growth">
                        <i class="fas fa-arrow-up mr-1"></i> {{ $prodCostGrowth }} vs last month
                    </div>
                </div>
            </a>
        </div>
    </div>

    <!-- Financial Overview -->
    <div class="compact-card card shadow mb-3">
        <div class="card-header d-flex align-items-center justify-content-between">
            <h6 class="m-0 font-weight-bold text-primary">
                <i class="fas fa-chart-pie mr-2"></i>Financial Overview - {{ date('F Y') }}
            </h6>
            <a href="{{ route('superadmin.report.customerreport') }}" class="btn btn-sm btn-outline-primary">View Reports</a>
        </div>
        <div class="card-body">
            <div class="row align-items-center">
                <div class="col-md-4">
                    <div class="financial-stat">
                        <div class="stat-value {{ $profitMargin >= 20 ? 'text-success' : ($profitMargin >= 10 ? 'text-warning' : 'text-danger') }}">
                            {{ $profitMargin }}%
                        </div>
                        <div class="stat-label">Profit Margin</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="financial-stat">
                        <div class="stat-value text-info">
                            {{ $expenseRatio }}%
                        </div>
                        <div class="stat-label">Expense Ratio</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="financial-stat">
                        <div class="stat-value {{ $grossProfit > 0 ? 'text-success' : 'text-danger' }}">
                            {{ $grossProfit > 0 ? '+' : '' }}{{ number_format($grossProfit) }}
                        </div>
                        <div class="stat-label">Net Position</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Row -->
    <div class="row mb-4">
        <!-- Revenue vs Expenses Chart -->
        <div class="col-lg-8 mb-3">
            <div class="chart-card card shadow h-100">
                <div class="card-header d-flex align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-chart-area mr-2"></i>Revenue vs Expenses (Last 6 Months)
                    </h6>
                    <div>
                        <button class="btn btn-sm btn-primary filter-btn active" data-filter="monthly">Monthly</button>
                        <button class="btn btn-sm btn-outline-primary filter-btn" data-filter="quarterly">Quarterly</button>
                    </div>
                </div>
                <div class="card-body">
                    <canvas id="revenueExpenseChart" height="100"></canvas>
                </div>
            </div>
        </div>

        <!-- Cost Breakdown Chart -->
        <div class="col-lg-4 mb-3">
            <div class="chart-card card shadow h-100">
                <div class="card-header">
                    <h6 class="m-0 font-weight-bold text-warning">
                        <i class="fas fa-chart-pie mr-2"></i>Cost Breakdown
                    </h6>
                </div>
                <div class="card-body d-flex align-items-center justify-content-center">
                    <canvas id="costBreakdownChart" height="180"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="compact-card card shadow mb-3">
        <div class="card-header">
            <h6 class="m-0 font-weight-bold text-info">
                <i class="fas fa-bolt mr-2"></i>Quick Actions
            </h6>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.invoice.invoiceorder') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-file-invoice text-primary"></i>
                            <div class="link-title">Invoices</div>
                        </div>
                    </a>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.salesmanagement.index') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-hand-holding-usd text-success"></i>
                            <div class="link-title">Sales Mgmt</div>
                        </div>
                    </a>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.purchase.index') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-shopping-cart text-warning"></i>
                            <div class="link-title">Purchase</div>
                        </div>
                    </a>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.grn.grnorder') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-truck-loading text-info"></i>
                            <div class="link-title">GRN</div>
                        </div>
                    </a>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.employee.employeepayroll') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-money-check-alt text-danger"></i>
                            <div class="link-title">Payroll</div>
                        </div>
                    </a>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.report.customerreport') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-chart-bar text-secondary"></i>
                            <div class="link-title">Reports</div>
                        </div>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Financial Summary & Pending Invoices -->
    <div class="row mb-3">
        <!-- Financial Summary -->
        <div class="col-md-4 mb-3">
            <div class="compact-card card shadow h-100">
                <div class="card-header">
                    <h6 class="m-0 font-weight-bold text-success">
                        <i class="fas fa-calculator mr-2"></i>Financial Summary
                    </h6>
                </div>
                <div class="card-body">
                    @foreach($summary as $row)
                        <div class="summary-item">
                            <span class="summary-label">{{ $row['title'] }}</span>
                            <span class="summary-value">{{ $row['value'] }}</span>
                        </div>
                    @endforeach
                </div>
            </div>
        </div>

        <!-- Pending Invoices -->
        <div class="col-md-8 mb-3">
            <div class="compact-card card shadow h-100">
                <div class="card-header d-flex align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-danger">
                        <i class="fas fa-clock mr-2"></i>Recent Invoices
                    </h6>
                    <a href="{{ route('superadmin.invoice.invoicedetails') }}" class="btn btn-sm btn-outline-danger">View All</a>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-sm table-hover mb-0">
                            <thead class="thead-light">
                                <tr>
                                    <th class="pl-3">Invoice No</th>
                                    <th>Date</th>
                                    <th>Reference</th>
                                    <th class="text-right">Amount</th>
                                    <th class="text-center pr-3">Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($pendingInvoices as $invoice)
                                    <tr>
                                        <td class="font-weight-bold pl-3">{{ $invoice->invoice_no }}</td>
                                        <td>{{ \Carbon\Carbon::parse($invoice->invoice_date)->format('d M Y') }}</td>
                                        <td>{{ $invoice->reference_no ?? '-' }}</td>
                                        <td class="text-right font-weight-bold">{{ number_format($invoice->total_amount, 2) }}</td>
                                        <td class="text-center pr-3">
                                            <span class="invoice-status pending">Pending</span>
                                        </td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="5" class="text-center text-muted py-3">
                                            <i class="fas fa-check-circle text-success mr-1"></i>
                                            No pending invoices
                                        </td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Cost Breakdown Table -->
    <div class="compact-card card shadow mb-3">
        <div class="card-header d-flex align-items-center justify-content-between">
            <h6 class="m-0 font-weight-bold text-secondary">
                <i class="fas fa-list-alt mr-2"></i>Cost Distribution Details
            </h6>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-sm table-hover mb-0">
                    <thead class="thead-light">
                        <tr>
                            <th class="pl-3">Cost Category</th>
                            <th class="text-right">Amount</th>
                            <th class="text-center">Percentage</th>
                            <th class="pr-3">Distribution</th>
                        </tr>
                    </thead>
                    <tbody>
                        @php
                            $totalCost = array_sum($costBreakdown);
                            $colors = ['primary', 'success', 'info', 'warning', 'danger'];
                            $colorIndex = 0;
                        @endphp
                        @foreach($costBreakdown as $category => $amount)
                            @php
                                $percentage = $totalCost > 0 ? round(($amount / $totalCost) * 100, 1) : 0;
                                $color = $colors[$colorIndex % count($colors)];
                                $colorIndex++;
                            @endphp
                            <tr>
                                <td class="font-weight-bold pl-3">{{ $category }}</td>
                                <td class="text-right">{{ number_format($amount, 2) }}</td>
                                <td class="text-center">{{ $percentage }}%</td>
                                <td class="pr-3">
                                    <div class="progress">
                                        <div class="progress-bar bg-{{ $color }}" style="width: {{ $percentage }}%"></div>
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                    <tfoot class="thead-light">
                        <tr class="font-weight-bold">
                            <td class="pl-3">Total</td>
                            <td class="text-right">{{ number_format($totalCost, 2) }}</td>
                            <td class="text-center">100%</td>
                            <td class="pr-3"></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>

</div>

@endsection

@section('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Pass PHP data to JS
    const months = @json($months);
    const chartRevenue = @json($chartRevenue);
    const chartExpenses = @json($chartExpenses);
    const costBreakdown = @json($costBreakdown);

    // Revenue vs Expenses Chart
    const revenueExpenseCtx = document.getElementById('revenueExpenseChart').getContext('2d');
    new Chart(revenueExpenseCtx, {
        type: 'line',
        data: {
            labels: months,
            datasets: [
                {
                    label: 'Revenue',
                    data: chartRevenue,
                    borderColor: '#1cc88a',
                    backgroundColor: 'rgba(28, 200, 138, 0.1)',
                    fill: true,
                    tension: 0.4,
                    borderWidth: 2,
                    pointBackgroundColor: '#1cc88a',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 4,
                    pointHoverRadius: 6
                },
                {
                    label: 'Expenses',
                    data: chartExpenses,
                    borderColor: '#e74a3b',
                    backgroundColor: 'rgba(231, 74, 59, 0.1)',
                    fill: true,
                    tension: 0.4,
                    borderWidth: 2,
                    pointBackgroundColor: '#e74a3b',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 4,
                    pointHoverRadius: 6
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    position: 'top',
                    labels: { usePointStyle: true, padding: 15, font: { size: 10 } }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: { color: 'rgba(0,0,0,0.05)' },
                    ticks: {
                        callback: function(value) {
                            return '' + value.toLocaleString();
                        }
                    }
                },
                x: {
                    grid: { display: false }
                }
            }
        }
    });

    // Cost Breakdown Doughnut Chart
    const costLabels = Object.keys(costBreakdown);
    const costData = Object.values(costBreakdown);

    const costCtx = document.getElementById('costBreakdownChart').getContext('2d');
    new Chart(costCtx, {
        type: 'doughnut',
        data: {
            labels: costLabels,
            datasets: [{
                data: costData,
                backgroundColor: [
                    '#4e73df', '#1cc88a', '#36b9cc', '#f6c23e', '#e74a3b',
                    '#858796', '#5a5c69', '#6f42c1'
                ],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        padding: 10,
                        usePointStyle: true,
                        font: { size: 10 }
                    }
                }
            },
            cutout: '60%'
        }
    });

    // Filter buttons functionality
    document.querySelectorAll('.filter-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('.filter-btn').forEach(b => {
                b.classList.remove('active', 'btn-primary');
                b.classList.add('btn-outline-primary');
            });
            this.classList.add('active', 'btn-primary');
            this.classList.remove('btn-outline-primary');
        });
    });

    // Dynamic Date/Time
    function updateDateTime() {
        const now = new Date();
        const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
        const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

        document.getElementById('day').textContent = days[now.getDay()];
        document.getElementById('daynum').textContent = now.getDate();
        document.getElementById('month').textContent = monthNames[now.getMonth()];
        document.getElementById('year').textContent = now.getFullYear();

        const timeStr = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
        document.querySelector('.display-time').textContent = timeStr;
    }
    updateDateTime();
    setInterval(updateDateTime, 1000);
});
</script>
@endsection
