@extends('layouts.sadmin')
@section('title', 'Subscription')

@section('content')
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="page-title mb-0">Subscription</h1>
        <p class="text-muted mb-0" style="font-size:13px">Manage company groups and tenant subscriptions</p>
    </div>
    <a href="{{ route('sadmin.companies.create') }}" class="btn btn-primary">
        <i class="bi bi-plus-circle me-1"></i>Add Company
    </a>
</div>

{{-- Search / Filter Bar --}}
<div class="card mb-3">
    <div class="card-body py-3">
        <form method="GET" action="{{ route('sadmin.companies') }}" class="row g-2 align-items-end">
            <div class="col-12 col-md-5">
                <label class="form-label mb-1" style="font-size:12px;font-weight:600">Search</label>
                <input type="text" name="search" class="form-control form-control-sm"
                       placeholder="Name, code or email…" value="{{ request('search') }}">
            </div>
            <div class="col-6 col-md-3">
                <label class="form-label mb-1" style="font-size:12px;font-weight:600">Status</label>
                <select name="status" class="form-select form-select-sm">
                    <option value="">All Statuses</option>
                    <option value="active"    {{ request('status')=='active'    ? 'selected':'' }}>Active</option>
                    <option value="trial"     {{ request('status')=='trial'     ? 'selected':'' }}>Trial</option>
                    <option value="suspended" {{ request('status')=='suspended' ? 'selected':'' }}>Suspended</option>
                    <option value="expired"   {{ request('status')=='expired'   ? 'selected':'' }}>Expired</option>
                </select>
            </div>
            <div class="col-6 col-md-2">
                <button type="submit" class="btn btn-primary btn-sm w-100">
                    <i class="bi bi-search me-1"></i>Search
                </button>
            </div>
            <div class="col-6 col-md-2">
                <a href="{{ route('sadmin.companies') }}" class="btn btn-outline-secondary btn-sm w-100">
                    <i class="bi bi-x me-1"></i>Clear
                </a>
            </div>
        </form>
    </div>
</div>

{{-- Stats Row --}}
<div class="row g-3 mb-3">
    @foreach([
        ['label'=>'Total',     'val'=>$companies->total(),                             'bg'=>'#EBF3FB','color'=>'#1B4F8A'],
        ['label'=>'Active',    'val'=>$companies->where('status','active')->count(),    'bg'=>'#d1e7dd','color'=>'#0a3622'],
        ['label'=>'Expired',   'val'=>$companies->where('status','expired')->count(),   'bg'=>'#f8d7da','color'=>'#842029'],
        ['label'=>'Inactive',  'val'=>$companies->whereIn('status',['suspended','trial'])->count(),'bg'=>'#e2e3e5','color'=>'#41464b'],
    ] as $stat)
    <div class="col-6 col-md-3">
        <div style="background:{{ $stat['bg'] }};border-radius:8px;padding:12px 16px;">
            <div style="font-size:11px;color:{{ $stat['color'] }};font-weight:700;letter-spacing:.5px;text-transform:uppercase">{{ $stat['label'] }}</div>
            <div style="font-size:22px;font-weight:700;color:{{ $stat['color'] }}">{{ $stat['val'] }}</div>
        </div>
    </div>
    @endforeach
</div>

{{-- Groups of Companies --}}
<div class="card mb-4">
    <div class="card-header d-flex flex-wrap justify-content-between align-items-center gap-2">
        <div>
            <div class="fw-semibold">Groups of Companies</div>
            <div class="text-muted" style="font-size:12px">Create groups to assign multiple companies under one umbrella.</div>
        </div>
        <div class="d-flex gap-2">
            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="window.print()">
                <i class="bi bi-printer me-1"></i>Print
            </button>
            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="exportTable('groupsTable','company-groups')">
                <i class="bi bi-download me-1"></i>Export
            </button>
            <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#newGroupModal">
                <i class="bi bi-plus-lg me-1"></i>New group
            </button>
        </div>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0" id="groupsTable">
                <thead>
                    <tr>
                        <th>Group ID</th>
                        <th>Group name</th>
                        <th>Member companies</th>
                        <th style="width:80px">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($groups as $group)
                    <tr>
                        <td><code>{{ $group->group_code }}</code></td>
                        <td class="fw-semibold">{{ $group->name }}</td>
                        <td style="font-size:13px">{{ $group->companies->pluck('name')->implode(', ') ?: '—' }}</td>
                        <td>
                            <form action="{{ route('sadmin.company-groups.destroy', $group) }}" method="POST"
                                  id="delete-group-{{ $group->id }}" class="d-inline">
                                @csrf @method('DELETE')
                                <button type="button" class="btn btn-outline-danger btn-sm btn-confirm"
                                        data-form="#delete-group-{{ $group->id }}"
                                        data-title="Delete group?"
                                        data-message="Companies in this group will be unassigned but not deleted."
                                        data-icon="warning" data-color="#E74C3C" data-confirm="Delete"
                                        title="Delete group">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </form>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="4" class="text-center text-muted py-4">No company groups yet. Create one to tag companies.</td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>
</div>

{{-- Companies --}}
<div class="card mb-2">
    <div class="card-header d-flex flex-wrap justify-content-between align-items-center gap-2">
        <div>
            <div class="fw-semibold">Companies</div>
            <div class="text-muted" style="font-size:12px">Click a row to open the company, or use the action buttons.</div>
        </div>
        <div class="d-flex gap-2">
            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="window.print()">
                <i class="bi bi-printer me-1"></i>Print
            </button>
            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="exportTable('companiesTable','companies')">
                <i class="bi bi-download me-1"></i>Export
            </button>
        </div>
    </div>
</div>
<div class="card">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0" id="companiesTable">
                <thead>
                    <tr>
                        <th style="width:30px">#</th>
                        <th>Company</th>
                        <th>Group</th>
                        <th>Code</th>
                        <th>Contact</th>
                        <th class="text-center">Users</th>
                        <th class="text-center">Concurrent</th>
                        <th>Status</th>
                        <th>Subscription / Trial</th>
                        <th style="width:110px">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($companies as $i => $company)
                    <tr>
                        <td class="text-muted" style="font-size:12px">{{ $companies->firstItem() + $i }}</td>
                        <td>
                            <div class="fw-semibold">{{ $company->name }}</div>
                            @if($company->country)
                                <div class="text-muted" style="font-size:11.5px">
                                    <i class="bi bi-geo-alt me-1"></i>{{ $company->country }}
                                </div>
                            @endif
                        </td>
                        <td style="font-size:12px">
                            @if($company->group)
                                <div><code>{{ $company->group->group_code }}</code></div>
                                <div class="text-muted">{{ $company->group->name }}</div>
                            @else
                                <span class="text-muted">—</span>
                            @endif
                        </td>
                        <td><code class="px-2 py-1 rounded" style="background:#f0f4f8;font-size:12.5px">{{ $company->company_code }}</code></td>
                        <td>
                            @if($company->email)
                                <div style="font-size:12.5px">{{ $company->email }}</div>
                            @endif
                            @if($company->phone)
                                <div class="text-muted" style="font-size:11.5px">{{ $company->phone }}</div>
                            @endif
                        </td>
                        <td class="text-center">
                            <span class="badge bg-light text-dark">{{ $company->users_count }}</span>
                        </td>
                        <td class="text-center">
                            <span class="badge bg-light text-dark">{{ $company->subscription?->max_concurrent_users ?? 5 }}</span>
                        </td>
                        <td>
                            <span class="status-pill status-{{ $company->status }}">
                                {{ ucfirst($company->status) }}
                            </span>
                        </td>
                        <td>
                            @if($company->subscription?->subscription_ends_at)
                                @php $exp = $company->subscription->subscription_ends_at; @endphp
                                <div style="font-size:12px" class="{{ $exp->isPast() ? 'text-danger fw-semibold' : 'text-muted' }}">
                                    <i class="bi bi-calendar3 me-1"></i>{{ $exp->format('d M Y') }}
                                    @if($exp->isPast())
                                        <span class="badge bg-danger ms-1" style="font-size:10px">Expired</span>
                                    @elseif($exp->diffInDays() <= 30)
                                        <span class="badge bg-warning text-dark ms-1" style="font-size:10px">{{ $exp->diffInDays() }}d left</span>
                                    @endif
                                </div>
                            @elseif($company->subscription?->trial_ends_at)
                                @php $trial = $company->subscription->trial_ends_at; @endphp
                                <div style="font-size:12px" class="{{ $trial->isPast() ? 'text-danger' : 'text-warning fw-semibold' }}">
                                    <i class="bi bi-clock me-1"></i>Trial: {{ $trial->format('d M Y') }}
                                    @if(!$trial->isPast())
                                        <span class="badge text-dark ms-1" style="font-size:10px;background:#fff3cd">{{ $trial->diffInDays() }}d left</span>
                                    @endif
                                </div>
                            @else
                                <span class="text-muted" style="font-size:12px">—</span>
                            @endif
                        </td>
                        <td>
                            <div class="d-flex gap-1">
                                <a href="{{ route('sadmin.companies.edit', $company) }}"
                                   class="btn btn-outline-primary btn-sm" title="Edit Company">
                                    <i class="bi bi-pencil-square"></i>
                                </a>

                                <form action="{{ route('sadmin.companies.toggle', $company) }}"
                                      method="POST" id="toggle-{{ $company->id }}" class="d-inline">
                                    @csrf @method('PATCH')
                                    <button type="button"
                                        class="btn btn-sm btn-confirm {{ $company->status === 'active' ? 'btn-outline-warning' : 'btn-outline-success' }}"
                                        data-form="#toggle-{{ $company->id }}"
                                        data-title="{{ $company->status === 'active' ? 'Suspend Company?' : 'Activate Company?' }}"
                                        data-message="This will {{ $company->status === 'active' ? 'prevent all users from logging in' : 'allow users to log in again' }}."
                                        data-icon="{{ $company->status === 'active' ? 'warning' : 'question' }}"
                                        data-color="{{ $company->status === 'active' ? '#E67E22' : '#27AE60' }}"
                                        data-confirm="{{ $company->status === 'active' ? 'Suspend' : 'Activate' }}"
                                        title="{{ $company->status === 'active' ? 'Suspend' : 'Activate' }}">
                                        <i class="bi bi-{{ $company->status === 'active' ? 'pause-circle' : 'play-circle' }}"></i>
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="10" class="text-center py-5">
                            <i class="bi bi-building display-6 d-block text-muted mb-2"></i>
                            <span class="text-muted">No companies found</span><br>
                            <a href="{{ route('sadmin.companies.create') }}" class="btn btn-primary btn-sm mt-3">
                                <i class="bi bi-plus me-1"></i>Create First Company
                            </a>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        @if($companies->hasPages())
            <div class="px-4 py-3 border-top">
                {{ $companies->withQueryString()->links() }}
            </div>
        @endif
    </div>
</div>

<div class="modal fade" id="newGroupModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form method="POST" action="{{ route('sadmin.company-groups.store') }}" class="modal-content">
            @csrf
            <div class="modal-header">
                <h5 class="modal-title">New company group</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <label class="form-label">Group name <span class="text-danger">*</span></label>
                <input type="text" name="name" class="form-control" placeholder="e.g. BDA" required>
                <div class="form-text">A unique Group ID (e.g. GRP-00001) is assigned automatically.</div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary">Create group</button>
            </div>
        </form>
    </div>
</div>
@endsection

@push('scripts')
<script>
function exportTable(tableId, filename) {
    const table = document.getElementById(tableId);
    if (!table) return;
    const rows = [...table.querySelectorAll('tr')].map(row =>
        [...row.querySelectorAll('th,td')].map(cell => '"' + cell.innerText.replace(/"/g, '""').trim() + '"').join(',')
    );
    const blob = new Blob([rows.join('\n')], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = filename + '.csv';
    link.click();
}
</script>
@endpush
