@extends('client.layouts.dashboard')

@section('title', 'Dashboard')

@section('styles')
<style>
    .stat-mini { font-size: 0.75rem; color: #6c757d; }
    .channel-badge {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        padding: 3px 8px;
        border-radius: 20px;
        font-size: 0.72rem;
        font-weight: 600;
    }
    .channel-sms { background: #e8f5e9; color: #2e7d32; }
    .channel-whatsapp { background: #e8f5e9; color: #128C7E; }
    .overview-card {
        border-radius: 12px;
        padding: 1.25rem;
        background: #fff;
        box-shadow: 0 2px 8px rgba(0,0,0,.04);
        border: 1px solid rgba(0,0,0,.06);
    }
    .overview-card .overview-icon {
        width: 44px;
        height: 44px;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.2rem;
    }
    .overview-card .overview-value {
        font-size: 1.5rem;
        font-weight: 700;
        line-height: 1.2;
    }
    .overview-card .overview-label {
        font-size: 0.78rem;
        color: #6c757d;
        margin-top: 2px;
    }
    .service-indicator {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        display: inline-block;
        margin-right: 6px;
    }
    .service-active { background-color: #28a745; }
    .service-inactive { background-color: #dc3545; }
    .top-user-rank {
        width: 26px;
        height: 26px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 0.72rem;
        font-weight: 700;
        color: #fff;
    }
    .rank-1 { background: linear-gradient(135deg, #f5af19, #f12711); }
    .rank-2 { background: linear-gradient(135deg, #bdc3c7, #2c3e50); }
    .rank-3 { background: linear-gradient(135deg, #b79891, #94716b); }
    .rank-default { background: #6c757d; }
</style>
@endsection

@section('content')
{{-- Row 1: Primary Stats --}}
<div class="row g-3 mb-4">
    <div class="col-6 col-lg-3">
        <div class="overview-card">
            <div class="d-flex align-items-center gap-3">
                <div class="overview-icon bg-primary bg-opacity-10 text-primary">
                    <i class="bi bi-people-fill"></i>
                </div>
                <div>
                    <div class="overview-value">{{ $stats['total_users'] }}</div>
                    <div class="overview-label">Total Users</div>
                    <div class="stat-mini">
                        <span class="text-success">{{ $stats['active_users'] }} active</span>
                        @if($stats['pending_users'] > 0)
                            · <span class="text-warning">{{ $stats['pending_users'] }} pending</span>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="overview-card">
            <div class="d-flex align-items-center gap-3">
                <div class="overview-icon bg-success bg-opacity-10 text-success">
                    <i class="bi bi-chat-dots-fill"></i>
                </div>
                <div>
                    <div class="overview-value">{{ $stats['sms_today'] }}</div>
                    <div class="overview-label">SMS Today</div>
                    <div class="stat-mini">{{ number_format($stats['total_sms']) }} total sent</div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="overview-card">
            <div class="d-flex align-items-center gap-3">
                <div class="overview-icon" style="background: rgba(18,140,126,.1); color: #128C7E;">
                    <i class="bi bi-whatsapp"></i>
                </div>
                <div>
                    <div class="overview-value">{{ $stats['whatsapp_today'] }}</div>
                    <div class="overview-label">WhatsApp Today</div>
                    <div class="stat-mini">{{ number_format($stats['total_whatsapp']) }} total sent</div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="overview-card">
            <div class="d-flex align-items-center gap-3">
                <div class="overview-icon bg-info bg-opacity-10 text-info">
                    <i class="bi bi-telephone-fill"></i>
                </div>
                <div>
                    <div class="overview-value">{{ $stats['calls_today'] }}</div>
                    <div class="overview-label">Calls Today</div>
                    <div class="stat-mini">{{ number_format($stats['total_calls']) }} total calls</div>
                </div>
            </div>
        </div>
    </div>
</div>

{{-- Row 2: Secondary Stats --}}
<div class="row g-3 mb-4">
    <div class="col-6 col-lg-3">
        <div class="overview-card">
            <div class="d-flex align-items-center gap-3">
                <div class="overview-icon" style="background: rgba(111,66,193,.1); color: #6f42c1;">
                    <i class="bi bi-envelope-fill"></i>
                </div>
                <div>
                    <div class="overview-value">{{ $stats['messages_today'] }}</div>
                    <div class="overview-label">All Messages Today</div>
                    <div class="stat-mini">{{ number_format($stats['total_messages']) }} lifetime</div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="overview-card">
            <div class="d-flex align-items-center gap-3">
                <div class="overview-icon bg-warning bg-opacity-10 text-warning">
                    <i class="bi bi-file-text-fill"></i>
                </div>
                <div>
                    <div class="overview-value">{{ $stats['active_templates'] }}</div>
                    <div class="overview-label">Active Templates</div>
                    <div class="stat-mini">{{ $stats['total_templates'] }} total</div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="overview-card">
            <div class="d-flex align-items-center gap-3">
                <div class="overview-icon bg-danger bg-opacity-10 text-danger">
                    <i class="bi bi-telephone-x-fill"></i>
                </div>
                <div>
                    <div class="overview-value">{{ $stats['missed_calls'] }}</div>
                    <div class="overview-label">Missed Calls</div>
                    <div class="stat-mini">
                        {{ $stats['incoming_calls'] }} in · {{ $stats['outgoing_calls'] }} out
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="overview-card">
            <div class="d-flex align-items-center gap-3">
                <div class="overview-icon bg-secondary bg-opacity-10 text-secondary">
                    <i class="bi bi-person-badge-fill"></i>
                </div>
                <div>
                    <div class="overview-value">{{ $stats['client_admins'] }}</div>
                    <div class="overview-label">Client Admins</div>
                    <div class="stat-mini">{{ $stats['rejected_users'] }} rejected users</div>
                </div>
            </div>
        </div>
    </div>
</div>

{{-- Row 3: Subscription + Usage + Quick Actions --}}
<div class="row g-3 mb-4">
    <div class="col-md-6 col-lg-4">
        <div class="overview-card h-100">
            <h6 class="text-muted mb-3"><i class="bi bi-credit-card me-2"></i>Subscription</h6>
            <div class="d-flex align-items-center gap-2 mb-3">
                <span class="badge bg-{{ $subscriptionInfo['type'] === 'trial' ? 'warning' : ($subscriptionInfo['type'] === 'premium' ? 'danger' : 'primary') }} px-3 py-2">
                    {{ ucfirst($subscriptionInfo['type']) }}
                </span>
                @if($subscriptionInfo['is_active'])
                    <span class="badge bg-success">Active</span>
                @else
                    <span class="badge bg-danger">Inactive</span>
                @endif
            </div>
            <div class="small text-muted">
                <div class="mb-1"><strong>Days Remaining:</strong>
                    <span class="{{ $subscriptionInfo['days_remaining'] <= 7 ? 'text-danger fw-bold' : '' }}">
                        {{ $subscriptionInfo['days_remaining'] }}
                    </span>
                </div>
                <div><strong>Expires:</strong> {{ $subscriptionInfo['ends_at'] ? $subscriptionInfo['ends_at']->format('M d, Y') : 'N/A' }}</div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-lg-4">
        <div class="overview-card h-100">
            <h6 class="text-muted mb-3"><i class="bi bi-speedometer2 me-2"></i>Usage Limits</h6>
            <div class="mb-3">
                <div class="d-flex justify-content-between mb-1">
                    <small>Users</small>
                    <small class="{{ $stats['total_users'] >= $client->max_users ? 'text-danger fw-bold' : '' }}">
                        {{ $stats['total_users'] }} / {{ $client->max_users }}
                    </small>
                </div>
                <div class="progress" style="height: 8px;">
                    @php $userPercent = $client->max_users > 0 ? ($stats['total_users'] / $client->max_users * 100) : 0 @endphp
                    <div class="progress-bar {{ $userPercent >= 90 ? 'bg-danger' : ($userPercent >= 70 ? 'bg-warning' : 'bg-primary') }}" style="width: {{ min($userPercent, 100) }}%"></div>
                </div>
            </div>
            <div class="mb-3">
                <div class="d-flex justify-content-between mb-1">
                    <small>Client Admins</small>
                    <small>{{ $stats['client_admins'] }} / {{ $client->max_client_admins }}</small>
                </div>
                <div class="progress" style="height: 8px;">
                    @php $adminPercent = $client->max_client_admins > 0 ? ($stats['client_admins'] / $client->max_client_admins * 100) : 0 @endphp
                    <div class="progress-bar {{ $adminPercent >= 90 ? 'bg-danger' : ($adminPercent >= 70 ? 'bg-warning' : 'bg-info') }}" style="width: {{ min($adminPercent, 100) }}%"></div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-12 col-lg-4">
        <div class="overview-card h-100">
            <h6 class="text-muted mb-3"><i class="bi bi-lightning me-2"></i>Quick Actions</h6>
            <div class="d-grid gap-2">
                <a href="{{ route('client.users.create') }}" class="btn btn-outline-primary btn-sm">
                    <i class="bi bi-person-plus me-2"></i>Add New User
                </a>
                <a href="{{ route('client.templates') }}" class="btn btn-outline-secondary btn-sm">
                    <i class="bi bi-file-text me-2"></i>Manage Templates
                </a>
                <a href="{{ route('client.sms-logs') }}" class="btn btn-outline-success btn-sm">
                    <i class="bi bi-chat-dots me-2"></i>Message Logs
                </a>
                <a href="{{ route('client.call-logs') }}" class="btn btn-outline-info btn-sm">
                    <i class="bi bi-telephone me-2"></i>Call Logs
                </a>
            </div>
        </div>
    </div>
</div>

{{-- Row 4: Charts --}}
<div class="row g-3 mb-4">
    <div class="col-lg-8">
        <div class="table-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-graph-up me-2"></i>Messaging Activity (7 Days)</h5>
                <div class="d-flex gap-2">
                    <span class="badge bg-success bg-opacity-10 text-success"><i class="bi bi-circle-fill me-1" style="font-size:.5rem"></i>SMS</span>
                    <span class="badge" style="background:rgba(18,140,126,.1);color:#128C7E"><i class="bi bi-circle-fill me-1" style="font-size:.5rem"></i>WhatsApp</span>
                </div>
            </div>
            <div class="card-body p-3">
                <canvas id="messageChart" height="180"></canvas>
            </div>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="table-card">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-telephone me-2"></i>Call Activity (7 Days)</h5>
            </div>
            <div class="card-body p-3">
                <canvas id="callChart" height="180"></canvas>
            </div>
        </div>
    </div>
</div>

{{-- Row 5: Top Users + Recent Messages --}}
<div class="row g-3 mb-4">
    {{-- Top Active Users --}}
    <div class="col-lg-5">
        <div class="table-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-trophy me-2"></i>Top Active Users</h5>
                <a href="{{ route('client.users') }}" class="btn btn-sm btn-outline-primary">View All</a>
            </div>
            <div class="table-responsive">
                <table class="table table-sm mb-0">
                    <thead>
                        <tr>
                            <th style="width:40px">#</th>
                            <th>User</th>
                            <th class="text-center">SMS</th>
                            <th class="text-center">WA</th>
                            <th class="text-center">Calls</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($topUsers as $index => $tUser)
                        <tr>
                            <td>
                                <div class="top-user-rank {{ $index < 3 ? 'rank-'.($index+1) : 'rank-default' }}">
                                    {{ $index + 1 }}
                                </div>
                            </td>
                            <td>
                                <div class="fw-semibold" style="font-size:.85rem">{{ $tUser->name }}</div>
                                <small class="text-muted">{{ $tUser->phone }}</small>
                            </td>
                            <td class="text-center">
                                <span class="fw-semibold">{{ $tUser->sms_count }}</span>
                            </td>
                            <td class="text-center">
                                <span class="fw-semibold">{{ $tUser->whatsapp_count }}</span>
                            </td>
                            <td class="text-center">
                                <span class="fw-semibold">{{ $tUser->call_count }}</span>
                            </td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="5" class="text-center text-muted py-4">No active users yet</td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    {{-- Recent Messages (SMS + WhatsApp combined) --}}
    <div class="col-lg-7">
        <div class="table-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-clock-history me-2"></i>Recent Messages</h5>
                <a href="{{ route('client.sms-logs') }}" class="btn btn-sm btn-outline-primary">View All</a>
            </div>
            <div class="table-responsive">
                <table class="table table-sm mb-0">
                    <thead>
                        <tr>
                            <th>User</th>
                            <th>Phone</th>
                            <th>Channel</th>
                            <th>Status</th>
                            <th>Time</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($recentMessages as $msg)
                        <tr>
                            <td>
                                <div style="font-size:.85rem">{{ $msg->user->name ?? 'Unknown' }}</div>
                            </td>
                            <td>
                                <small>{{ $msg->phone_number }}</small>
                            </td>
                            <td>
                                @if($msg->channel === 'whatsapp')
                                    <span class="channel-badge channel-whatsapp">
                                        <i class="bi bi-whatsapp"></i> WhatsApp
                                    </span>
                                @else
                                    <span class="channel-badge channel-sms">
                                        <i class="bi bi-chat-dots"></i> SMS
                                    </span>
                                @endif
                            </td>
                            <td>
                                @if($msg->status === 'sent')
                                    <span class="badge bg-success bg-opacity-10 text-success">Sent</span>
                                @elseif($msg->status === 'pending')
                                    <span class="badge bg-warning bg-opacity-10 text-warning">Pending</span>
                                @else
                                    <span class="badge bg-danger bg-opacity-10 text-danger">Failed</span>
                                @endif
                            </td>
                            <td>
                                <small class="text-muted">{{ $msg->created_at->diffForHumans() }}</small>
                            </td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="5" class="text-center text-muted py-4">No messages yet</td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

{{-- Row 6: Recent Users --}}
<div class="row g-3">
    <div class="col-12">
        <div class="table-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-people me-2"></i>Recent Users</h5>
                <a href="{{ route('client.users') }}" class="btn btn-sm btn-outline-primary">View All</a>
            </div>
            <div class="table-responsive">
                <table class="table table-sm mb-0">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Phone</th>
                            <th>Status</th>
                            <th>Active</th>
                            <th>Created</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($recentUsers as $user)
                        <tr>
                            <td>
                                <div class="fw-semibold">{{ $user->name }}</div>
                                <small class="text-muted">{{ $user->email }}</small>
                            </td>
                            <td><small>{{ $user->phone }}</small></td>
                            <td>
                                @if($user->approval_status === 'pending')
                                    <span class="badge badge-pending">Pending</span>
                                @elseif($user->approval_status === 'approved')
                                    <span class="badge badge-approved">Approved</span>
                                @else
                                    <span class="badge badge-rejected">Rejected</span>
                                @endif
                            </td>
                            <td>
                                @if($user->is_active)
                                    <span class="service-indicator service-active"></span>Yes
                                @else
                                    <span class="service-indicator service-inactive"></span>No
                                @endif
                            </td>
                            <td>
                                <small class="text-muted">{{ $user->created_at->diffForHumans() }}</small>
                            </td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="5" class="text-center text-muted py-4">No users yet</td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script>
    // Combined Messaging Chart (SMS + WhatsApp)
    const msgCtx = document.getElementById('messageChart').getContext('2d');
    new Chart(msgCtx, {
        type: 'line',
        data: {
            labels: @json($chartData['labels']),
            datasets: [
                {
                    label: 'SMS',
                    data: @json($chartData['sms']),
                    borderColor: '#11998e',
                    backgroundColor: 'rgba(17, 153, 142, 0.08)',
                    fill: true,
                    tension: 0.4,
                    borderWidth: 2,
                    pointRadius: 3,
                    pointHoverRadius: 5
                },
                {
                    label: 'WhatsApp',
                    data: @json($chartData['whatsapp']),
                    borderColor: '#128C7E',
                    backgroundColor: 'rgba(18, 140, 126, 0.08)',
                    fill: true,
                    tension: 0.4,
                    borderWidth: 2,
                    borderDash: [5, 3],
                    pointRadius: 3,
                    pointHoverRadius: 5
                }
            ]
        },
        options: {
            responsive: true,
            interaction: {
                mode: 'index',
                intersect: false
            },
            plugins: {
                legend: {
                    display: true,
                    position: 'bottom',
                    labels: {
                        usePointStyle: true,
                        padding: 20
                    }
                },
                tooltip: {
                    callbacks: {
                        footer: function(items) {
                            let total = items.reduce((sum, item) => sum + item.raw, 0);
                            return 'Total: ' + total;
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: { precision: 0 }
                }
            }
        }
    });

    // Call Activity Chart
    const callCtx = document.getElementById('callChart').getContext('2d');
    new Chart(callCtx, {
        type: 'bar',
        data: {
            labels: @json($chartData['labels']),
            datasets: [{
                label: 'Calls',
                data: @json($chartData['calls']),
                backgroundColor: 'rgba(13, 202, 240, 0.3)',
                borderColor: '#0dcaf0',
                borderWidth: 1,
                borderRadius: 4
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: { display: false }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: { precision: 0 }
                }
            }
        }
    });
</script>
@endsection