<?php
require_once __DIR__ . '/src/auth.php';
require_once __DIR__ . '/src/db.php';
require_once __DIR__ . '/src/history.php';
require_login();

$pdo = get_db_connection();
$message = '';

// Garantir coluna para tipo (Cliente/Fornecedor)
try {
    $col = $pdo->query("SHOW COLUMNS FROM suppliers LIKE 'party_type'")->fetch();
    if (!$col) {
        $pdo->exec("ALTER TABLE suppliers ADD COLUMN party_type VARCHAR(20) NOT NULL DEFAULT 'Fornecedor' AFTER name");
    }
} catch (Throwable $e) {
}

// Handle Create/Update Supplier
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? null;
    $name = $_POST['name'];
    $party_type = $_POST['party_type'] ?? 'Fornecedor';
    $party_type = ($party_type === 'Cliente') ? 'Cliente' : 'Fornecedor';
    $tax_id = $_POST['tax_id'];
    $contact_person = $_POST['contact_person'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];

    if ($id) {
        $stmt = $pdo->prepare("UPDATE suppliers SET name=?, party_type=?, tax_id=?, contact_person=?, email=?, phone=? WHERE id=?");
        if ($stmt->execute([$name, $party_type, $tax_id, $contact_person, $email, $phone, $id])) {
            $message = "Cliente/Fornecedor atualizado com sucesso!";
        }
    } else {
        $stmt = $pdo->prepare("INSERT INTO suppliers (name, party_type, tax_id, contact_person, email, phone) VALUES (?, ?, ?, ?, ?, ?)");
        if ($stmt->execute([$name, $party_type, $tax_id, $contact_person, $email, $phone])) {
            $message = "Cliente/Fornecedor cadastrado com sucesso!";
        }
    }
}

// Handle Delete Supplier
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $stmt = $pdo->prepare("DELETE FROM suppliers WHERE id=?");
    if ($stmt->execute([$id])) {
        $message = "Cliente/Fornecedor excluído com sucesso!";
    }
}

$suppliers = $pdo->query("SELECT * FROM suppliers ORDER BY name ASC")->fetchAll();

require_once __DIR__ . '/templates/header.php';
?>

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Gerenciar Clientes/Fornecedores</h2>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#supplierModal">
            <i class="fas fa-plus"></i> Novo Cliente/Fornecedor
        </button>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-success"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>

    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Tipo</th>
                            <th>Nome</th>
                            <th>CNPJ/CPF</th>
                            <th>Contato</th>
                            <th>E-mail</th>
                            <th>Telefone</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($suppliers as $s): ?>
                        <tr>
                            <td><?= htmlspecialchars($s['party_type'] ?? 'Fornecedor') ?></td>
                            <td><?= htmlspecialchars($s['name']) ?></td>
                            <td><?= htmlspecialchars($s['tax_id'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($s['contact_person'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($s['email'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($s['phone'] ?? '-') ?></td>
                            <td>
                                <button class="btn btn-sm btn-warning" onclick="editSupplier(<?= htmlspecialchars(json_encode($s)) ?>)">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <a href="suppliers.php?delete=<?= $s['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Tem certeza?')">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Modal Fornecedor -->
<div class="modal fade" id="supplierModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="id" id="supplier-id">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">Novo Cliente/Fornecedor</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label>Tipo</label>
                        <select name="party_type" id="supplier-party-type" class="form-select" required>
                            <option value="Fornecedor" selected>Fornecedor</option>
                            <option value="Cliente">Cliente</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label>Nome / Razão Social</label>
                        <input type="text" name="name" id="supplier-name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label>CNPJ / CPF</label>
                        <input type="text" name="tax_id" id="supplier-tax-id" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label>Pessoa de Contato</label>
                        <input type="text" name="contact_person" id="supplier-contact" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label>E-mail</label>
                        <input type="email" name="email" id="supplier-email" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label>Telefone</label>
                        <input type="text" name="phone" id="supplier-phone" class="form-control">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Salvar</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function editSupplier(s) {
    document.getElementById('modalTitle').innerText = 'Editar Cliente/Fornecedor';
    document.getElementById('supplier-id').value = s.id;
    document.getElementById('supplier-party-type').value = s.party_type || 'Fornecedor';
    document.getElementById('supplier-name').value = s.name;
    document.getElementById('supplier-tax-id').value = s.tax_id || '';
    document.getElementById('supplier-contact').value = s.contact_person || '';
    document.getElementById('supplier-email').value = s.email || '';
    document.getElementById('supplier-phone').value = s.phone || '';
    
    new bootstrap.Modal(document.getElementById('supplierModal')).show();
}

// Reset modal on close
document.getElementById('supplierModal').addEventListener('hidden.bs.modal', function () {
    document.getElementById('modalTitle').innerText = 'Novo Cliente/Fornecedor';
    document.getElementById('supplier-id').value = '';
    document.getElementById('supplier-party-type').value = 'Fornecedor';
    document.getElementById('supplier-name').value = '';
    document.getElementById('supplier-tax-id').value = '';
    document.getElementById('supplier-contact').value = '';
    document.getElementById('supplier-email').value = '';
    document.getElementById('supplier-phone').value = '';
});
</script>

<?php require_once __DIR__ . '/templates/footer.php'; ?>
