@include('layouts.header')

<!-- BEGIN: Content-->
<div class="app-content content">
    <div class="content-overlay"></div>
    <div class="header-navbar-shadow"></div>
    <div class="content-wrapper">
<div class="content-header row">
    <div class="content-header-left col-md-6 col-12 mb-2">
        <h3 class="content-header-title mb-0">API Token Management</h3>
        <div class="row breadcrumbs-top">
            <div class="breadcrumb-wrapper col-12">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Home</a></li>
                    <li class="breadcrumb-item active">API Tokens</li>
                </ol>
            </div>
        </div>
    </div>
    <div class="content-header-right col-md-6 col-12">
        <button type="button" class="btn btn-primary float-right" data-bs-toggle="modal" data-bs-target="#createTokenModal">
            <i class="feather icon-plus"></i> Generate New Token
        </button>
        <a href="{{ route('api.documentation') }}" class="btn btn-info float-right mr-1">
            <i class="feather icon-book"></i> API Documentation
        </a>
    </div>
</div>

<div class="content-body">
    <!-- Alert for newly created token -->
    @if(session('new_token'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <h4 class="alert-heading"><i class="feather icon-check-circle"></i> Token Created Successfully!</h4>
        <p>Please copy your new API token. <strong>For security reasons, it won't be shown again.</strong></p>
        <div class="input-group mt-2">
            <input type="text" class="form-control" id="newTokenValue" value="{{ session('new_token') }}" readonly>
            <div class="input-group-append">
                <button class="btn btn-outline-primary" type="button" onclick="copyToken()">
                    <i class="feather icon-copy"></i> Copy
                </button>
            </div>
        </div>
        <button type="button" class="close" data-bs-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    @endif

    @if(session('success'))
    <div class="alert alert-success alert-dismissible fade show">
        {{ session('success') }}
        <button type="button" class="close" data-bs-dismiss="alert">&times;</button>
    </div>
    @endif

    @if(session('error'))
    <div class="alert alert-danger alert-dismissible fade show">
        {{ session('error') }}
        <button type="button" class="close" data-bs-dismiss="alert">&times;</button>
    </div>
    @endif

    <!-- API Tokens List -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title">Your API Tokens</h4>
                    <p class="text-muted">Manage your API tokens for external integrations like Ultimate POS, e-commerce platforms, etc.</p>
                </div>
                <div class="card-content">
                    <div class="card-body">
                        @if($tokens->count() > 0)
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>Abilities</th>
                                        <th>Created</th>
                                        <th>Last Used</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($tokens as $token)
                                    <tr>
                                        <td>
                                            <strong>{{ $token->name }}</strong>
                                            <br>
                                            <small class="text-muted">ID: {{ $token->id }}</small>
                                        </td>
                                        <td>
                                            @if(in_array('*', $token->abilities))
                                                <span class="badge badge-primary">Full Access</span>
                                            @else
                                                <span class="badge badge-secondary">{{ count($token->abilities) }} permissions</span>
                                            @endif
                                        </td>
                                        <td>{{ $token->created_at->format('M d, Y H:i') }}</td>
                                        <td>
                                            @if($token->last_used_at)
                                                {{ $token->last_used_at->diffForHumans() }}
                                            @else
                                                <span class="text-muted">Never</span>
                                            @endif
                                        </td>
                                        <td>
                                            @if($token->last_used_at && $token->last_used_at->gt(now()->subHour()))
                                                <span class="badge badge-success">Active</span>
                                            @else
                                                <span class="badge badge-secondary">Inactive</span>
                                            @endif
                                        </td>
                                        <td>
                                            <div class="btn-group" role="group">
                                                <button type="button" class="btn btn-sm btn-info" onclick="viewToken({{ $token->id }})">
                                                    <i class="feather icon-eye"></i> View
                                                </button>
                                                <button type="button" class="btn btn-sm btn-danger" onclick="revokeToken({{ $token->id }}, '{{ $token->name }}')">
                                                    <i class="feather icon-trash-2"></i> Revoke
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                        @else
                        <div class="text-center py-5">
                            <i class="feather icon-key" style="font-size: 48px; color: #ccc;"></i>
                            <h4 class="mt-3">No API Tokens Yet</h4>
                            <p class="text-muted">Create your first API token to start integrating with external applications.</p>
                            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createTokenModal">
                                <i class="feather icon-plus"></i> Generate First Token
                            </button>
                        </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Start Guide -->
    <div class="row">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title"><i class="feather icon-zap text-warning"></i> Quick Start</h4>
                </div>
                <div class="card-body">
                    <ol class="pl-3">
                        <li class="mb-2">Click "Generate New Token" button above</li>
                        <li class="mb-2">Give your token a descriptive name (e.g., "Ultimate POS Integration")</li>
                        <li class="mb-2">Copy the token immediately (it won't be shown again)</li>
                        <li class="mb-2">Get your Device ID from the devices page</li>
                        <li class="mb-2">Use the token in your API requests with headers:
                            <pre class="mt-1 p-2 bg-light"><code>Authorization: Bearer YOUR_TOKEN
X-Device-ID: YOUR_DEVICE_ID</code></pre>
                        </li>
                    </ol>
                    <a href="{{ route('api.documentation') }}" class="btn btn-primary btn-block mt-2">
                        <i class="feather icon-book"></i> View Full Documentation
                    </a>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title"><i class="feather icon-info text-info"></i> Your Devices</h4>
                </div>
                <div class="card-body">
                    @if($devices->count() > 0)
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Device ID</th>
                                    <th>Sender</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($devices as $device)
                                <tr>
                                    <td><strong>{{ $device->id }}</strong></td>
                                    <td>{{ $device->sender ?? 'N/A' }}</td>
                                    <td>
                                        <span class="badge badge-{{ $device->status === 'ONLINE' ? 'success' : 'secondary' }}">
                                            {{ $device->status }}
                                        </span>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                    <p class="text-muted small mt-2">
                        <i class="feather icon-alert-circle"></i> Use these Device IDs in the X-Device-ID header when making API requests.
                    </p>
                    @else
                    <p class="text-muted">No devices found. Please add a device first.</p>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Create Token Modal -->
<div class="modal fade" id="createTokenModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form action="{{ route('api.tokens.store') }}" method="POST">
                @csrf
                <div class="modal-header" style="background-color: #fd810e;">
                    <h5 class="modal-title text-white"><i class="feather icon-key"></i> Generate New API Token</h5>
                    <button type="button" class="close text-white" data-bs-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="tokenName">Token Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="tokenName" name="name" required
                               placeholder="e.g., Ultimate POS Integration">
                        <small class="text-muted">Give your token a descriptive name to identify its purpose.</small>
                    </div>

                    <div class="form-group">
                        <label for="abilities">Permissions</label>
                        <select multiple class="form-control" id="abilities" name="abilities[]" size="5">
                            <option value="*" selected>Full Access (All Permissions)</option>
                            <option value="tickets:create">Create Tickets</option>
                            <option value="tickets:read">Read Tickets</option>
                            <option value="tickets:update">Update Tickets</option>
                            <option value="statistics:read">View Statistics</option>
                        </select>
                        <small class="text-muted">Hold Ctrl/Cmd to select multiple. Leave "Full Access" for complete API access.</small>
                    </div>

                    <div class="alert alert-warning">
                        <i class="feather icon-alert-triangle"></i> 
                        <strong>Important:</strong> The token will only be displayed once. Make sure to copy it immediately.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="feather icon-key"></i> Generate Token
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- View Token Details Modal -->
<div class="modal fade" id="viewTokenModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header" style="background-color: #fd810e;">
                <h5 class="modal-title text-white"><i class="feather icon-info"></i> Token Details</h5>
                <button type="button" class="close text-white" data-bs-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body" id="tokenDetailsBody">
                <p class="text-center"><i class="feather icon-loader spinning"></i> Loading...</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
function copyToken() {
    const tokenInput = document.getElementById('newTokenValue');
    tokenInput.select();
    tokenInput.setSelectionRange(0, 99999);
    document.execCommand('copy');
    
    // Show feedback
    const btn = event.target.closest('button');
    const originalHTML = btn.innerHTML;
    btn.innerHTML = '<i class="feather icon-check"></i> Copied!';
    btn.classList.add('btn-success');
    
    setTimeout(() => {
        btn.innerHTML = originalHTML;
        btn.classList.remove('btn-success');
    }, 2000);
}

function viewToken(tokenId) {
    $('#viewTokenModal').modal('show');
    $('#tokenDetailsBody').html('<p class="text-center"><i class="feather icon-loader spinning"></i> Loading...</p>');
    
    fetch(`/api-tokens/${tokenId}`)
        .then(response => response.json())
        .then(data => {
            const html = `
                <table class="table table-bordered">
                    <tr>
                        <th width="40%">Name</th>
                        <td>${data.name}</td>
                    </tr>
                    <tr>
                        <th>Abilities</th>
                        <td>${data.abilities.join(', ')}</td>
                    </tr>
                    <tr>
                        <th>Created At</th>
                        <td>${data.created_at}</td>
                    </tr>
                    <tr>
                        <th>Last Used At</th>
                        <td>${data.last_used_at || 'Never'}</td>
                    </tr>
                    <tr>
                        <th>Expires At</th>
                        <td>${data.expires_at || 'Never'}</td>
                    </tr>
                </table>
            `;
            $('#tokenDetailsBody').html(html);
        })
        .catch(error => {
            $('#tokenDetailsBody').html('<p class="text-danger">Failed to load token details.</p>');
        });
}

function revokeToken(tokenId, tokenName) {
    if (confirm(`Are you sure you want to revoke the token "${tokenName}"?\n\nThis action cannot be undone. Any applications using this token will immediately lose access.`)) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = `/api-tokens/${tokenId}`;
        
        const csrfInput = document.createElement('input');
        csrfInput.type = 'hidden';
        csrfInput.name = '_token';
        csrfInput.value = '{{ csrf_token() }}';
        
        const methodInput = document.createElement('input');
        methodInput.type = 'hidden';
        methodInput.name = '_method';
        methodInput.value = 'DELETE';
        
        form.appendChild(csrfInput);
        form.appendChild(methodInput);
        document.body.appendChild(form);
        form.submit();
    }
}

// Auto-dismiss success alert after 10 seconds
setTimeout(() => {
    $('.alert-success').fadeOut('slow');
}, 10000);
</script>

    </div>
</div>
<!-- END: Content-->

@include('layouts.footer')
