<?php
ob_start();
?>

<div class="row mb-4">
    <div class="col-md-12">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="<?= url('/dashboard') ?>">Dashboard</a></li>
                <li class="breadcrumb-item active">Contas a Receber</li>
            </ol>
        </nav>
        <h2><i class="bi bi-arrow-down-circle me-2"></i> Contas a Receber</h2>
    </div>
</div>

<!-- Cards de Resumo -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card bg-primary text-white">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h6 class="card-title">Total a Receber</h6>
                        <h4 class="mb-0">R$ <?= number_format($resumo['total_receber'] ?? 0, 2, ',', '.') ?></h4>
                    </div>
                    <div class="align-self-center">
                        <i class="bi bi-currency-dollar display-6"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-success text-white">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h6 class="card-title">Recebido</h6>
                        <h4 class="mb-0">R$ <?= number_format($resumo['total_recebido'] ?? 0, 2, ',', '.') ?></h4>
                    </div>
                    <div class="align-self-center">
                        <i class="bi bi-check-circle display-6"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-warning text-white">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h6 class="card-title">Vencidas</h6>
                        <h4 class="mb-0">R$ <?= number_format($resumo['total_vencidas'] ?? 0, 2, ',', '.') ?></h4>
                    </div>
                    <div class="align-self-center">
                        <i class="bi bi-exclamation-triangle display-6"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-info text-white">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h6 class="card-title">Vencendo Hoje</h6>
                        <h4 class="mb-0">R$ <?= number_format($resumo['vencendo_hoje'] ?? 0, 2, ',', '.') ?></h4>
                    </div>
                    <div class="align-self-center">
                        <i class="bi bi-clock display-6"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-list-ul me-2"></i> Lista de Contas</h5>
                <div class="d-flex gap-2">
                    <button class="btn btn-outline-secondary" onclick="filtrarContas()">
                        <i class="bi bi-funnel"></i> Filtrar
                    </button>
                    <a href="<?= url('/entradas/criar') ?>" class="btn btn-primary">
                        <i class="bi bi-plus-circle me-2"></i> Nova Conta
                    </a>
                </div>
            </div>
            <div class="card-body">
                <!-- Filtros -->
                <div class="row mb-3" id="filtrosContas" style="display: none;">
                    <form method="GET" action="<?= url('/entradas') ?>" id="formFiltros">
                        <div class="row">
                            <div class="col-md-3">
                                <label for="filtroStatus" class="form-label">Status</label>
                                <select class="form-select" id="filtroStatus" name="status">
                                    <option value="">Todos</option>
                                    <option value="pendente" <?= ($filtros['status'] ?? '') === 'pendente' ? 'selected' : '' ?>>Pendente</option>
                                    <option value="pago_parcial" <?= ($filtros['status'] ?? '') === 'pago_parcial' ? 'selected' : '' ?>>Pago Parcial</option>
                                    <option value="pago" <?= ($filtros['status'] ?? '') === 'pago' ? 'selected' : '' ?>>Pago</option>
                                    <option value="vencido" <?= ($filtros['status'] ?? '') === 'vencido' ? 'selected' : '' ?>>Vencido</option>
                                    <option value="cancelado" <?= ($filtros['status'] ?? '') === 'cancelado' ? 'selected' : '' ?>>Cancelado</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label for="filtroCliente" class="form-label">Cliente</label>
                                <input type="text" class="form-control" id="filtroCliente" name="cliente"
                                    placeholder="Nome ou documento..." value="<?= htmlspecialchars($filtros['cliente'] ?? '') ?>">
                            </div>
                            <div class="col-md-3">
                                <label for="filtroDataInicio" class="form-label">Vencimento Início</label>
                                <input type="date" class="form-control" id="filtroDataInicio" name="data_inicio"
                                    value="<?= htmlspecialchars($filtros['data_inicio'] ?? '') ?>">
                            </div>
                            <div class="col-md-3">
                                <label for="filtroDataFim" class="form-label">Vencimento Fim</label>
                                <input type="date" class="form-control" id="filtroDataFim" name="data_fim"
                                    value="<?= htmlspecialchars($filtros['data_fim'] ?? '') ?>">
                            </div>
                        </div>
                        <div class="row mt-2">
                            <div class="col-md-12">
                                <button type="submit" class="btn btn-primary btn-sm">
                                    <i class="bi bi-search me-1"></i> Filtrar
                                </button>
                                <a href="<?= url('/entradas') ?>" class="btn btn-outline-secondary btn-sm">
                                    <i class="bi bi-x-circle me-1"></i> Limpar
                                </a>
                            </div>
                        </div>
                    </form>
                </div>

                <!-- Tabela -->
                <div class="table-responsive">
                    <table class="table table-hover" id="tabelaContas">
                        <thead class="table-light">
                            <tr>
                                <th>Cliente</th>
                                <th>Descrição</th>
                                <th>Vencimento</th>
                                <th>Valor</th>
                                <th>Status</th>
                                <th width="120">Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($contas)): ?>
                                <?php foreach ($contas as $conta): ?>
                                    <?php
                                    $hoje = date('Y-m-d');
                                    $isOverdue = ($conta['due_date'] < $hoje) && ($conta['status'] !== 'pago');
                                    $diasAtraso = $isOverdue ? (int)((strtotime($hoje) - strtotime($conta['due_date'])) / (60 * 60 * 24)) : 0;
                                    $diasRestantes = (int)((strtotime($conta['due_date']) - strtotime($hoje)) / (60 * 60 * 24));
                                    ?>
                                    <tr class="<?= $conta['status'] === 'vencido' ? 'table-danger' : ($isOverdue ? 'table-warning' : '') ?>">
                                        <td>
                                            <div>
                                                <strong><?= htmlspecialchars($conta['customer_name']) ?></strong>
                                                <?php if ($conta['customer_document']): ?>
                                                    <br><small class="text-muted"><?= htmlspecialchars($conta['customer_document']) ?></small>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td>
                                            <?= htmlspecialchars($conta['description']) ?>
                                            <?php if ($conta['reference']): ?>
                                                <br><small class="text-muted">Ref: <?= htmlspecialchars($conta['reference']) ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?= date('d/m/Y', strtotime($conta['due_date'])) ?>
                                            <?php if ($isOverdue): ?>
                                                <br><small class="text-danger">
                                                    <strong><?= $diasAtraso ?> dia(s) em atraso</strong>
                                                </small>
                                            <?php elseif ($diasRestantes == 0): ?>
                                                <br><small class="text-danger">
                                                    <strong>VENCE HOJE!</strong>
                                                </small>
                                            <?php elseif ($diasRestantes <= 3 && $diasRestantes > 0): ?>
                                                <br><small class="text-warning">
                                                    Vence em <?= $diasRestantes ?> dia(s)
                                                </small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <strong class="text-<?= $conta['status'] === 'pago' ? 'success' : 'primary' ?>">
                                                R$ <?= number_format($conta['amount'], 2, ',', '.') ?>
                                            </strong>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?= $conta['status'] === 'pago' ? 'success' : ($conta['status'] === 'vencido' ? 'danger' : ($conta['status'] === 'cancelado' ? 'secondary' : 'warning')) ?>">
                                                <?= ucfirst($conta['status']) ?>
                                            </span>
                                            <?php if (!empty($conta['shipay_charge_id'])): ?>
                                                <br>
                                                <span class="badge bg-info mt-1" title="Boleto Shipay gerado">
                                                    <i class="bi bi-receipt me-1"></i> Shipay
                                                </span>
                                                <?php if (!empty($conta['shipay_status'])): ?>
                                                    <br>
                                                    <small class="text-muted">Status: <?= htmlspecialchars($conta['shipay_status']) ?></small>
                                                <?php endif; ?>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div class="btn-group btn-group-sm" role="group">
                                                <?php if ($conta['status'] === 'pendente'): ?>
                                                    <button class="btn btn-outline-success"
                                                            onclick="receberConta(<?= $conta['id'] ?>)"
                                                            title="Receber">
                                                        <i class="bi bi-check"></i>
                                                    </button>
                                                <?php endif; ?>
                                                <a href="<?= url('/entradas/editar?id=' . $conta['id']) ?>"
                                                   class="btn btn-outline-primary" title="Editar">
                                                    <i class="bi bi-pencil"></i>
                                                </a>
                                                <button class="btn btn-outline-info"
                                                        onclick="visualizarConta(<?= $conta['id'] ?>)"
                                                        title="Visualizar">
                                                    <i class="bi bi-eye"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6" class="text-center text-muted py-4">
                                        <i class="bi bi-arrow-down-circle display-6 d-block mb-2"></i>
                                        Nenhuma conta a receber encontrada
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Mostrar filtros se houver algum filtro ativo
    <?php if (!empty($filtros['status']) || !empty($filtros['cliente']) || !empty($filtros['data_inicio']) || !empty($filtros['data_fim'])): ?>
        $('#filtrosContas').show();
    <?php endif; ?>
});

function filtrarContas() {
    $('#filtrosContas').toggle();
}

function receberConta(id) {
    Swal.fire({
        title: 'Confirmar Recebimento',
        text: 'Deseja marcar esta conta como recebida?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Sim, receber',
        cancelButtonText: 'Cancelar',
        confirmButtonColor: '#28a745'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: appUrl('/entradas/receber'),
                type: 'POST',
                data: { id: id },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Sucesso!',
                            text: response.message,
                            showConfirmButton: false,
                            timer: 1500
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Erro',
                            text: response.message
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        icon: 'error',
                        title: 'Erro',
                        text: 'Erro ao processar recebimento'
                    });
                }
            });
        }
    });
}

function visualizarConta(id) {
    window.open(appUrl('/entradas/visualizar?id=' + id), '_blank');
}
</script>

<?php
$content = ob_get_clean();
$activeMenu = 'contas-receber';
include ROOT_PATH . '/views/layouts/app.php';
?>
