<?php
$isEdit = isset($conta['id']);
$pessoas = $pessoas ?? [];
$metodosPagamento = $metodosPagamento ?? [];
$contasBancarias = $contasBancarias ?? [];
$planoContas = $planoContas ?? [];
$centroCustos = $centroCustos ?? [];
?>

<div class="row">
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header">
                <i class="bi bi-receipt me-2"></i> Dados da Conta a Receber
            </div>
            <div class="card-body">
                <div class="row">
                    <!-- Cliente -->
                    <div class="col-md-12 mb-3">
                        <label for="pessoa_id" class="form-label">Cliente</label>
                        <select class="form-select" id="pessoa_id" name="pessoa_id">
                            <option value="">Selecione um cliente...</option>
                            <?php if (!empty($pessoas)): ?>
                                <?php foreach ($pessoas as $pessoa): ?>
                                    <option value="<?= $pessoa['id'] ?>"
                                        <?= ($conta['pessoa_id'] ?? '') == $pessoa['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($pessoa['name'] ?? $pessoa['nome'] ?? '') ?>
                                        <?php if (!empty($pessoa['document'])): ?>
                                            - <?= htmlspecialchars($pessoa['document']) ?>
                                        <?php endif; ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                    </div>

                    <!-- Número/Número do Documento -->
                    <div class="col-md-4 mb-3">
                        <label for="numero" class="form-label">Número do Documento</label>
                        <input type="text" class="form-control" id="numero" name="numero"
                            placeholder="Ex: 001/2025"
                            value="<?= htmlspecialchars($conta['numero'] ?? '') ?>">
                    </div>

                    <!-- Descrição -->
                    <div class="col-md-8 mb-3">
                        <label for="description" class="form-label">Descrição *</label>
                        <input type="text" class="form-control" id="description" name="description"
                            placeholder="Ex: Venda de produtos, Serviço prestado..."
                            value="<?= htmlspecialchars($conta['description'] ?? '') ?>" required>
                    </div>

                    <!-- Valores -->
                    <div class="col-md-4 mb-3">
                        <label for="amount" class="form-label">Valor Total (R$) *</label>
                        <input type="number" class="form-control" id="amount" name="amount"
                            step="0.01" min="0.01" placeholder="0,00" required
                            value="<?= $conta['amount'] ?? '' ?>">
                    </div>

                    <?php if ($isEdit): ?>
                    <div class="col-md-4 mb-3">
                        <label for="amount_paid" class="form-label">Valor Pago (R$)</label>
                        <input type="number" class="form-control" id="amount_paid" name="amount_paid"
                            step="0.01" min="0" placeholder="0,00"
                            value="<?= $conta['amount_paid'] ?? $conta['amount_received'] ?? '0.00' ?>">
                    </div>

                    <div class="col-md-4 mb-3">
                        <label class="form-label">Valor Restante (R$)</label>
                        <input type="text" class="form-control" id="amount_remaining" readonly
                            value="<?= number_format($conta['amount_remaining'] ?? 0, 2, ',', '.') ?>">
                    </div>
                    <?php else: ?>
                    <div class="col-md-8 mb-3">
                        <label class="form-label">Valor Restante (R$)</label>
                        <input type="text" class="form-control" id="amount_remaining" readonly
                            value="<?= number_format($conta['amount'] ?? 0, 2, ',', '.') ?>">
                    </div>
                    <?php endif; ?>

                    <!-- Datas -->
                    <div class="col-md-6 mb-3">
                        <label for="due_date" class="form-label">Data de Vencimento *</label>
                        <input type="date" class="form-control" id="due_date" name="due_date"
                            value="<?= $conta['due_date'] ?? '' ?>" required>
                    </div>

                    <div class="col-md-6 mb-3">
                        <label for="payment_date" class="form-label">Data de Pagamento</label>
                        <input type="date" class="form-control" id="payment_date" name="payment_date"
                            value="<?= $conta['payment_date'] ?? '' ?>">
                    </div>

                    <!-- Status -->
                    <div class="col-md-6 mb-3">
                        <label for="status" class="form-label">Status *</label>
                        <select class="form-select" id="status" name="status" required>
                            <option value="pendente" <?= ($conta['status'] ?? 'pendente') === 'pendente' ? 'selected' : '' ?>>Pendente</option>
                            <option value="pago_parcial" <?= ($conta['status'] ?? '') === 'pago_parcial' ? 'selected' : '' ?>>Pago Parcial</option>
                            <option value="pago" <?= ($conta['status'] ?? '') === 'pago' ? 'selected' : '' ?>>Pago</option>
                            <option value="vencido" <?= ($conta['status'] ?? '') === 'vencido' ? 'selected' : '' ?>>Vencido</option>
                            <option value="cancelado" <?= ($conta['status'] ?? '') === 'cancelado' ? 'selected' : '' ?>>Cancelado</option>
                        </select>
                    </div>

                    <!-- Método de Pagamento -->
                    <div class="col-md-6 mb-3">
                        <label for="metodo_pagamento_id" class="form-label">Método de Pagamento</label>
                        <select class="form-select" id="metodo_pagamento_id" name="metodo_pagamento_id">
                            <option value="">Selecione...</option>
                            <?php if (!empty($metodosPagamento)): ?>
                                <?php foreach ($metodosPagamento as $metodo): ?>
                                    <option value="<?= $metodo['id'] ?>"
                                        <?= ($conta['metodo_pagamento_id'] ?? $conta['payment_method_id'] ?? '') == $metodo['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($metodo['nome'] ?? $metodo['name'] ?? '') ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                    </div>

                    <!-- Conta Bancária -->
                    <div class="col-md-6 mb-3">
                        <label for="conta_bancaria_id" class="form-label">Conta Bancária</label>
                        <select class="form-select" id="conta_bancaria_id" name="conta_bancaria_id">
                            <option value="">Selecione...</option>
                            <?php if (!empty($contasBancarias)): ?>
                                <?php foreach ($contasBancarias as $contaBancaria): ?>
                                    <option value="<?= $contaBancaria['id'] ?>"
                                        <?= ($conta['conta_bancaria_id'] ?? '') == $contaBancaria['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($contaBancaria['banco'] ?? '') ?>
                                        - <?= htmlspecialchars($contaBancaria['agencia'] ?? '') ?>
                                        / <?= htmlspecialchars($contaBancaria['conta'] ?? '') ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                    </div>

                    <!-- Plano de Contas -->
                    <div class="col-md-6 mb-3">
                        <label for="plano_conta_id" class="form-label">Plano de Contas</label>
                        <select class="form-select" id="plano_conta_id" name="plano_conta_id">
                            <option value="">Selecione...</option>
                            <?php if (!empty($planoContas)): ?>
                                <?php foreach ($planoContas as $plano): ?>
                                    <option value="<?= $plano['id'] ?>"
                                        <?= ($conta['plano_conta_id'] ?? '') == $plano['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($plano['codigo'] ?? '') ?> - <?= htmlspecialchars($plano['nome'] ?? $plano['name'] ?? '') ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                    </div>

                    <!-- Centro de Custo -->
                    <div class="col-md-6 mb-3">
                        <label for="centro_custo_id" class="form-label">Centro de Custo</label>
                        <select class="form-select" id="centro_custo_id" name="centro_custo_id">
                            <option value="">Selecione...</option>
                            <?php if (!empty($centroCustos)): ?>
                                <?php foreach ($centroCustos as $centro): ?>
                                    <option value="<?= $centro['id'] ?>"
                                        <?= ($conta['centro_custo_id'] ?? '') == $centro['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($centro['code'] ?? '') ?> - <?= htmlspecialchars($centro['name'] ?? '') ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </select>
                    </div>

                    <!-- Observações -->
                    <div class="col-md-12 mb-3">
                        <label for="notes" class="form-label">Observações</label>
                        <textarea class="form-control" id="notes" name="notes" rows="3"
                            placeholder="Observações sobre esta conta..."><?= htmlspecialchars($conta['notes'] ?? '') ?></textarea>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <!-- Informações -->
        <div class="card mb-3">
            <div class="card-header">
                <i class="bi bi-info-circle me-2"></i> Informações
            </div>
            <div class="card-body">
                <p class="small text-muted mb-2">
                    <i class="bi bi-asterisk text-danger"></i> Campos obrigatórios
                </p>
                <?php if ($isEdit): ?>
                <hr>
                <p class="small text-muted mb-1">
                    <strong>Criado em:</strong><br>
                    <?= date('d/m/Y H:i', strtotime($conta['created_at'])) ?>
                </p>
                <?php if (!empty($conta['updated_at']) && $conta['updated_at'] != $conta['created_at']): ?>
                <p class="small text-muted mb-1">
                    <strong>Atualizado em:</strong><br>
                    <?= date('d/m/Y H:i', strtotime($conta['updated_at'])) ?>
                </p>
                <?php endif; ?>
                <?php if (!empty($conta['payment_date'])): ?>
                <p class="small text-muted">
                    <strong>Pago em:</strong><br>
                    <?= date('d/m/Y', strtotime($conta['payment_date'])) ?>
                </p>
                <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>

        <!-- Resumo Financeiro (somente na edição) -->
        <?php if ($isEdit && isset($conta['amount'])): ?>
        <div class="card">
            <div class="card-header">
                <i class="bi bi-calculator me-2"></i> Resumo Financeiro
            </div>
            <div class="card-body">
                <div class="d-flex justify-content-between mb-2">
                    <span class="text-muted">Valor Total:</span>
                    <strong>R$ <?= number_format($conta['amount'], 2, ',', '.') ?></strong>
                </div>
                <div class="d-flex justify-content-between mb-2">
                    <span class="text-muted">Valor Pago:</span>
                    <strong class="text-success">R$ <?= number_format($conta['amount_paid'] ?? $conta['amount_received'] ?? 0, 2, ',', '.') ?></strong>
                </div>
                <hr>
                <div class="d-flex justify-content-between">
                    <span class="text-muted"><strong>Restante:</strong></span>
                    <strong class="text-primary">R$ <?= number_format($conta['amount_remaining'] ?? 0, 2, ',', '.') ?></strong>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php if ($isEdit): ?>
<input type="hidden" name="id" value="<?= $conta['id'] ?>">
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Calcular valor restante automaticamente
    const amountInput = document.getElementById('amount');
    const amountPaidInput = document.getElementById('amount_paid');
    const amountRemainingInput = document.getElementById('amount_remaining');

    function calcularRestante() {
        const total = parseFloat(amountInput.value || 0);
        const pago = parseFloat(amountPaidInput?.value || 0);
        const restante = total - pago;

        if (amountRemainingInput) {
            amountRemainingInput.value = restante.toFixed(2).replace('.', ',');
        }
    }

    if (amountInput) {
        amountInput.addEventListener('input', calcularRestante);
    }
    if (amountPaidInput) {
        amountPaidInput.addEventListener('input', calcularRestante);
    }

});
</script>