@extends('accounting.layouts.app')

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

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="page-header">
                <h1>Module Sync Dashboard</h1>
                <p>Synchronize data from other modules to accounting</p>
            </div>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-12">
            <button class="btn btn-primary" onclick="syncAll()">
                <i class="fas fa-sync-alt me-2"></i>Sync All Modules
            </button>
        </div>
    </div>

    <div class="row" id="syncCards">
        <!-- Sync cards will be loaded here -->
    </div>
</div>

@push('scripts')
<script>
    $(document).ready(function() {
        loadSyncStatus();
    });

    function loadSyncStatus() {
        $.get('/accounting/sync/status', function(response) {
            if (response.success) {
                renderSyncCards(response.status);
            }
        });
    }

    function renderSyncCards(status) {
        let html = '';
        
        const modules = {
            'reservations': { name: 'Reservations', icon: 'fa-bed', color: 'purple' },
            'pos_orders': { name: 'POS Orders', icon: 'fa-utensils', color: 'green' },
            'service_requests': { name: 'Service Requests', icon: 'fa-concierge-bell', color: 'orange' },
            'purchase_orders': { name: 'Purchase Orders', icon: 'fa-truck', color: 'red' },
            'expenses': { name: 'Expenses', icon: 'fa-money-bill', color: 'blue' }
        };

        for (let [key, data] of Object.entries(status)) {
            const moduleInfo = modules[key] || { name: key, icon: 'fa-database', color: 'purple' };
            
            html += `
                <div class="col-md-6 col-lg-4 mb-4">
                    <div class="sync-card">
                        <div class="sync-card-header">
                            <div class="sync-icon ${moduleInfo.color}">
                                <i class="fas ${moduleInfo.icon}"></i>
                            </div>
                            <div>
                                <h3>${moduleInfo.name}</h3>
                                <p class="text-muted">Total: ${data.total}</p>
                            </div>
                        </div>
                        <div class="sync-card-body">
                            <div class="pending-count">
                                <span class="label">Pending Sync</span>
                                <span class="value ${data.pending_count > 0 ? 'warning' : 'success'}">
                                    ${data.pending_count}
                                </span>
                            </div>
                            <div class="last-sync">
                                <small>Last sync: ${data.last_sync ? new Date(data.last_sync).toLocaleString() : 'Never'}</small>
                            </div>
                        </div>
                        <div class="sync-card-footer">
                            <button class="btn-sync" onclick="syncModule('${key}')">
                                <i class="fas fa-sync-alt"></i>
                                <span>Sync Now</span>
                            </button>
                        </div>
                    </div>
                </div>
            `;
        }

        $('#syncCards').html(html);
    }

    function syncModule(module) {
        Swal.fire({
            title: 'Sync Module',
            text: `Sync ${module.replace('_', ' ')} data to accounting?`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Sync',
            showLoaderOnConfirm: true,
            preConfirm: () => {
                return fetch(`/accounting/sync/${module}`, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                        'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        Swal.fire('Success', `Synced ${data.synced_count} items totaling UGX ${data.total_amount?.toLocaleString() || 0}`, 'success');
                        loadSyncStatus();
                    } else {
                        throw new Error(data.error || 'Sync failed');
                    }
                })
                .catch(error => {
                    Swal.fire('Error', error.message, 'error');
                });
            }
        });
    }

    function syncAll() {
        Swal.fire({
            title: 'Sync All Modules',
            text: 'This will sync all pending data to accounting. Continue?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Sync All',
            showLoaderOnConfirm: true,
            preConfirm: () => {
                return fetch('/accounting/sync/all', {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                        'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        let message = 'Sync completed:\n';
                        for (let [module, result] of Object.entries(data.results)) {
                            if (result.success) {
                                message += `\n${module.replace('_', ' ')}: ${result.synced_count} items (UGX ${result.total_amount?.toLocaleString() || 0})`;
                            }
                        }
                        Swal.fire('Success', message, 'success');
                        loadSyncStatus();
                    } else {
                        throw new Error('Sync failed');
                    }
                })
                .catch(error => {
                    Swal.fire('Error', error.message, 'error');
                });
            }
        });
    }
</script>
@endpush

@push('styles')
<style>
    .sync-card {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.02);
        overflow: hidden;
        transition: transform 0.2s;
        height: 100%;
        display: flex;
        flex-direction: column;
    }

    .sync-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 10px 25px rgba(0,0,0,0.05);
    }

    .sync-card-header {
        padding: 1.5rem;
        display: flex;
        align-items: center;
        gap: 1rem;
        border-bottom: 1px solid #f1f5f9;
    }

    .sync-icon {
        width: 50px;
        height: 50px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.5rem;
    }

    .sync-icon.purple { background: #e9efff; color: #4361ee; }
    .sync-icon.green { background: #e3f7ec; color: #10b981; }
    .sync-icon.orange { background: #fff2e0; color: #f97316; }
    .sync-icon.red { background: #fee9e9; color: #ef4444; }
    .sync-icon.blue { background: #e1f0fe; color: #3b82f6; }

    .sync-card-header h3 {
        margin: 0;
        font-size: 1.2rem;
        font-weight: 600;
        color: #1e293b;
    }

    .sync-card-body {
        padding: 1.5rem;
        flex: 1;
    }

    .pending-count {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 0.5rem;
    }

    .pending-count .label {
        color: #64748b;
        font-size: 0.9rem;
    }

    .pending-count .value {
        font-size: 1.5rem;
        font-weight: 700;
    }

    .pending-count .value.warning {
        color: #f97316;
    }

    .pending-count .value.success {
        color: #10b981;
    }

    .last-sync {
        color: #94a3b8;
        font-size: 0.8rem;
    }

    .sync-card-footer {
        padding: 1rem 1.5rem;
        border-top: 1px solid #f1f5f9;
    }

    .btn-sync {
        width: 100%;
        padding: 0.8rem;
        background: #f1f5f9;
        border: none;
        border-radius: 10px;
        color: #475569;
        font-weight: 500;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 0.5rem;
        transition: all 0.2s;
        cursor: pointer;
    }

    .btn-sync:hover {
        background: #4361ee;
        color: white;
    }

    .btn-sync:hover i {
        transform: rotate(180deg);
        transition: transform 0.3s;
    }
</style>
@endpush
@endsection