<?php
require_once __DIR__ . '/../includes/config.php';

if (!isset($_SESSION['user_id']) || !isset($_SESSION['store_id'])) {
    header('Location: /pages/login.php');
    exit;
}

$pdo = getDB();
$userId = $_SESSION['user_id'];
$storeId = $_SESSION['store_id'];

$storeStmt = $pdo->prepare("SELECT * FROM stores WHERE id = ? LIMIT 1");
$storeStmt->execute([$storeId]);
$store = $storeStmt->fetch(PDO::FETCH_ASSOC);

if (!$store) { header('Location: /dashboard.php'); exit; }

$successMessage = null;
$errorMessage = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'update_origin') {
        $originZipcode = preg_replace('/\D/', '', $_POST['origin_zipcode'] ?? '');
        $originCity = trim($_POST['origin_city'] ?? '');
        $originState = strtoupper(trim($_POST['origin_state'] ?? ''));
        $handlingTime = max(0, intval($_POST['handling_time'] ?? 0));
        if (strlen($originZipcode) === 8) {
            $pdo->prepare("UPDATE stores SET origin_zipcode=?, origin_city=?, origin_state=?, handling_time=? WHERE id=?")->execute([$originZipcode, $originCity, $originState, $handlingTime, $storeId]);
            $storeStmt->execute([$storeId]); $store = $storeStmt->fetch(PDO::FETCH_ASSOC);
            $successMessage = 'Endereço salvo!';
        } else { $errorMessage = 'CEP inválido'; }
    }
    
    if ($action === 'add_method') {
        $name = trim($_POST['method_name'] ?? '');
        if ($name) {
            $pdo->prepare("INSERT INTO shipping_methods (store_id, name, type, min_order_value, is_active) VALUES (?, ?, ?, ?, 1)")->execute([$storeId, $name, $_POST['method_type'] ?? 'manual', floatval($_POST['min_order_value'] ?? 0) ?: null]);
            $successMessage = 'Método criado!';
        }
    }
    
    if ($action === 'add_zone') {
        $methodId = intval($_POST['method_id'] ?? 0);
        $zipcodeStart = preg_replace('/\D/', '', $_POST['zipcode_start'] ?? '');
        $zipcodeEnd = preg_replace('/\D/', '', $_POST['zipcode_end'] ?? '');
        if ($methodId && strlen($zipcodeStart) === 8 && strlen($zipcodeEnd) === 8) {
            $pdo->prepare("INSERT INTO shipping_zones (store_id, shipping_method_id, name, zipcode_start, zipcode_end, price, min_days, max_days) VALUES (?,?,?,?,?,?,?,?)")->execute([$storeId, $methodId, trim($_POST['zone_name'] ?? ''), $zipcodeStart, $zipcodeEnd, floatval($_POST['zone_price'] ?? 0), max(0, intval($_POST['min_days'] ?? 1)), max(1, intval($_POST['max_days'] ?? 5))]);
            $successMessage = 'Zona criada!';
        }
    }
    
    if ($action === 'toggle_method') { $pdo->prepare("UPDATE shipping_methods SET is_active = NOT is_active WHERE id = ? AND store_id = ?")->execute([intval($_POST['method_id'] ?? 0), $storeId]); }
    if ($action === 'delete_zone') { $pdo->prepare("DELETE FROM shipping_zones WHERE id = ? AND store_id = ?")->execute([intval($_POST['zone_id'] ?? 0), $storeId]); $successMessage = 'Zona removida!'; }
    if ($action === 'edit_zone') { $zid = intval($_POST['zone_id'] ?? 0); $pdo->prepare("UPDATE shipping_zones SET name=?, zipcode_start=?, zipcode_end=?, price=?, min_days=?, max_days=? WHERE id=? AND store_id=?")->execute([trim($_POST['zone_name'] ?? ''), preg_replace('/\D/', '', $_POST['zipcode_start'] ?? ''), preg_replace('/\D/', '', $_POST['zipcode_end'] ?? ''), floatval($_POST['zone_price'] ?? 0), intval($_POST['min_days'] ?? 1), intval($_POST['max_days'] ?? 5), $zid, $storeId]); $successMessage = 'Zona atualizada!'; }
    if ($action === 'delete_method') { $mid = intval($_POST['method_id'] ?? 0); $pdo->prepare("DELETE FROM shipping_zones WHERE shipping_method_id = ? AND store_id = ?")->execute([$mid, $storeId]); $pdo->prepare("DELETE FROM shipping_methods WHERE id = ? AND store_id = ?")->execute([$mid, $storeId]); $successMessage = 'Método removido!'; }
    if ($action === 'edit_method') { $mid = intval($_POST['method_id'] ?? 0); $pdo->prepare("UPDATE shipping_methods SET name=?, type=?, min_order_value=? WHERE id=? AND store_id=?")->execute([trim($_POST['method_name'] ?? ''), $_POST['method_type'] ?? 'manual', floatval($_POST['min_order_value'] ?? 0), $mid, $storeId]); $successMessage = 'Método atualizado!'; }
    
    if ($action === 'save_integration') {
        $provider = $_POST['provider'] ?? '';
        $apiToken = trim($_POST['api_token'] ?? '');
        $sandboxMode = isset($_POST['sandbox_mode']) ? 1 : 0;
        if ($provider) {
            if (!empty($apiToken)) {
                $pdo->prepare("INSERT INTO shipping_integrations (store_id, provider, api_token, sandbox_mode, is_active) VALUES (?, ?, ?, ?, 1) ON DUPLICATE KEY UPDATE api_token = VALUES(api_token), sandbox_mode = VALUES(sandbox_mode)")->execute([$storeId, $provider, $apiToken, $sandboxMode]);
                $successMessage = 'Integração salva!';
            } else {
                $pdo->prepare("UPDATE shipping_integrations SET sandbox_mode = ? WHERE store_id = ? AND provider = ?")->execute([$sandboxMode, $storeId, $provider]);
                $successMessage = 'Configuração atualizada!';
            }
        }
    }
    
    if ($action === 'disconnect_integration') {
        $provider = $_POST['provider'] ?? '';
        if ($provider) {
            $pdo->prepare("DELETE FROM shipping_integrations WHERE store_id = ? AND provider = ?")->execute([$storeId, $provider]);
            $successMessage = 'Integração desconectada!';
        }
    }
    
    if ($action === 'upload_csv' && isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === UPLOAD_ERR_OK) {
        $methodId = intval($_POST['csv_method_id'] ?? 0);
        if ($methodId) {
            $file = fopen($_FILES['csv_file']['tmp_name'], 'r');
            fgetcsv($file, 0, ';');
            $imported = 0;
            while (($row = fgetcsv($file, 0, ';')) !== false) {
                if (count($row) >= 4) {
                    $cepStart = preg_replace('/\D/', '', $row[1]);
                    $cepEnd = preg_replace('/\D/', '', $row[2]);
                    $price = floatval(str_replace([',', 'R$', ' '], ['.', '', ''], $row[3]));
                    if (strlen($cepStart) === 8 && strlen($cepEnd) === 8 && $price > 0) {
                        $pdo->prepare("INSERT INTO shipping_zones (store_id, shipping_method_id, name, zipcode_start, zipcode_end, price, min_days, max_days) VALUES (?,?,?,?,?,?,?,?)")->execute([$storeId, $methodId, trim($row[0]), $cepStart, $cepEnd, $price, intval($row[4] ?? 1), intval($row[5] ?? 5)]);
                        $imported++;
                    }
                }
            }
            fclose($file);
            $successMessage = "$imported zonas importadas!";
        }
    }
}

$methodsStmt = $pdo->prepare("SELECT * FROM shipping_methods WHERE store_id = ? ORDER BY priority, name");
$methodsStmt->execute([$storeId]);
$shippingMethods = $methodsStmt->fetchAll(PDO::FETCH_ASSOC);

$zonesStmt = $pdo->prepare("SELECT sz.*, sm.name as method_name FROM shipping_zones sz JOIN shipping_methods sm ON sz.shipping_method_id = sm.id WHERE sz.store_id = ? ORDER BY sm.name, sz.zipcode_start");
$zonesStmt->execute([$storeId]);
$shippingZones = $zonesStmt->fetchAll(PDO::FETCH_ASSOC);

$intStmt = $pdo->prepare("SELECT * FROM shipping_integrations WHERE store_id = ?");
$intStmt->execute([$storeId]);
$integrationsMap = array_column($intStmt->fetchAll(PDO::FETCH_ASSOC), null, 'provider');

$step1OK = !empty($store['origin_zipcode']);
$step2OK = count($shippingMethods) > 0;
$step3OK = count($shippingZones) > 0 || isset($integrationsMap['melhor_envio']);

$pageTitle = 'Configurar Frete';
include __DIR__ . '/../includes/dashboard-header.php';
?>
<?php include __DIR__ . '/../includes/responsive-styles.php'; ?>
<style>
.main-content { width: 100% !important; }
.frete-page { width: 800px; min-width: 800px; max-width: 100%; margin: 0 auto; }
.frete-page > * { width: 100% !important; max-width: 100% !important; box-sizing: border-box !important; }
.setup-stepper { display: flex; justify-content: space-between; margin-bottom: 2rem; padding: 1.5rem; background: var(--card-bg, #fff); border-radius: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); }
.step-item { display: flex; align-items: center; gap: 0.75rem; flex: 1; }
.step-number { width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 700; background: var(--bg); color: var(--text-muted); border: 2px solid var(--border-color); flex-shrink: 0; }
.step-item.complete .step-number { background: var(--primary); color: #fff; border-color: var(--primary); }
.step-title { font-weight: 600; font-size: 0.9rem; color: var(--text); }
.step-desc { font-size: 0.75rem; color: var(--text-muted); }
.section-card { width: 100%; box-sizing: border-box; background: var(--card-bg, #fff); border-radius: 16px; margin-bottom: 1.5rem; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.06); }
.section-header { display: flex; min-height: 60px; align-items: center; justify-content: space-between; padding: 1.25rem 1.5rem; background: linear-gradient(135deg, rgba(var(--primary-rgb), 0.08), rgba(var(--primary-rgb), 0.02)); border-bottom: 1px solid var(--border-color); cursor: pointer; }
.section-card:has(.section-body[style*="display:none"]) .section-header, .section-card:has(.section-body[style*="display: none"]) .section-header { border-bottom: none; }
.section-title { display: flex; align-items: center; gap: 0.75rem; }
.section-title iconify-icon { font-size: 1.4rem; color: var(--primary); }
.section-title h3 { margin: 0; font-size: 1.1rem; font-weight: 600; }
.section-badge { padding: 0.25rem 0.75rem; border-radius: 20px; font-size: 0.75rem; font-weight: 600; }
.section-badge.complete { background: rgba(16, 185, 129, 0.15); color: #10b981; }
.section-badge.pending { background: rgba(245, 158, 11, 0.15); color: #f59e0b; }
.section-body { padding: 1.5rem; overflow: hidden; }
.guide-box { background: linear-gradient(135deg, #f0f9ff, #e0f2fe); border: 1px solid #bae6fd; border-radius: 12px; padding: 1rem 1.25rem; margin-bottom: 1.25rem; display: flex; align-items: flex-start; gap: 0.75rem; }
.guide-box iconify-icon { font-size: 1.25rem; color: #0284c7; flex-shrink: 0; }
.guide-box p { margin: 0; font-size: 0.9rem; color: #0369a1; line-height: 1.5; }
.form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; }
.form-group { margin-bottom: 0; }
.form-group label { display: block; font-size: 0.85rem; font-weight: 500; color: var(--text); margin-bottom: 0.5rem; }
.form-control { width: 100%; padding: 0.75rem 1rem; border: 1.5px solid var(--border-color); border-radius: 10px; font-size: 0.95rem; background: var(--bg); transition: all 0.2s; }
.form-control:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(var(--primary-rgb), 0.15); }
.form-help { font-size: 0.8rem; color: var(--text-muted); margin-top: 0.35rem; }
.btn-save { display: inline-flex; align-items: center; gap: 0.5rem; padding: 0.75rem 1.5rem; background: var(--primary); color: #fff; border: none; border-radius: 10px; font-weight: 600; cursor: pointer; transition: all 0.2s; }
.btn-save:hover { opacity: 0.9; transform: translateY(-1px); }
.btn-add { display: inline-flex; align-items: center; gap: 0.5rem; padding: 0.5rem 1rem; background: rgba(var(--primary-rgb), 0.1); color: var(--primary); border: 1.5px dashed var(--primary); border-radius: 10px; font-weight: 600; cursor: pointer; }
.simple-table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
.simple-table th { text-align: left; padding: 0.75rem; background: var(--bg); font-weight: 600; color: var(--text-muted); font-size: 0.8rem; text-transform: uppercase; }
.simple-table td { padding: 0.85rem 0.75rem; border-bottom: 1px solid var(--border-color); }
.empty-state { text-align: center; padding: 2.5rem; color: var(--text-muted); }
.empty-state iconify-icon { font-size: 3rem; opacity: 0.4; margin-bottom: 0.75rem; display: block; }
.type-tabs { display: flex; gap: 0.5rem; margin-bottom: 1.5rem; border-bottom: 2px solid var(--border-color); padding-bottom: 0.5rem; }
.type-tab { padding: 0.75rem 1.25rem; border: none; background: transparent; color: var(--text-muted); font-weight: 500; cursor: pointer; border-radius: 8px 8px 0 0; }
.type-tab.active { background: var(--primary); color: #fff; }
.integration-card { border: 2px solid var(--border-color); border-radius: 12px; padding: 1.25rem; margin-bottom: 1rem; }
.integration-card.connected { border-color: #10b981; background: rgba(16, 185, 129, 0.03); }
.integration-header { display: flex; align-items: center; gap: 1rem; margin-bottom: 1rem; }
.integration-status { margin-left: auto; padding: 0.25rem 0.75rem; border-radius: 20px; font-size: 0.75rem; font-weight: 600; }
.integration-status.connected { background: rgba(16, 185, 129, 0.15); color: #10b981; }
.modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.5); display: none; align-items: center; justify-content: center; z-index: 9999; }
.modal-overlay.active { display: flex; }
.modal-box { background: var(--card-bg, #fff); border-radius: 16px; max-width: 500px; width: 95%; max-height: 90vh; overflow-y: auto; }
.modal-header { display: flex; justify-content: space-between; align-items: center; padding: 1.25rem 1.5rem; border-bottom: 1px solid var(--border-color); }
.modal-header h3 { margin: 0; font-size: 1.1rem; }
.modal-close { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: var(--text-muted); }
.modal-body { padding: 1.5rem; }
.modal-footer { padding: 1rem 1.5rem; border-top: 1px solid var(--border-color); display: flex; gap: 0.75rem; justify-content: flex-end; }
.alert { padding: 1rem 1.25rem; border-radius: 10px; margin-bottom: 1rem; display: flex; align-items: center; gap: 0.75rem; }
.alert-success { background: rgba(16, 185, 129, 0.1); color: #059669; }
.alert-error { background: rgba(239, 68, 68, 0.1); color: #dc2626; }
@media (max-width: 768px) { .setup-stepper { flex-direction: column; gap: 1rem; } .form-grid { grid-template-columns: 1fr; } }
</style>

<div class="dashboard-layout">
    <?php include __DIR__ . '/../includes/dashboard-sidebar.php'; ?>
    <main class="main-content">
        <div class="page-header">
            <div class="page-title">
                <h1><iconify-icon icon="solar:delivery-bold"></iconify-icon> Configurar Frete</h1>
                <p class="page-subtitle">Configure como os clientes receberão os produtos</p>
            </div>
        </div>

        <?php if ($successMessage): ?><div class="alert alert-success"><iconify-icon icon="solar:check-circle-bold"></iconify-icon> <?= htmlspecialchars($successMessage) ?></div><?php endif; ?>
        <?php if ($errorMessage): ?><div class="alert alert-error"><iconify-icon icon="solar:close-circle-bold"></iconify-icon> <?= htmlspecialchars($errorMessage) ?></div><?php endif; ?>

        <div class="frete-page">
            <!-- Stepper -->
            <div class="setup-stepper">
                <div class="step-item <?= $step1OK ? 'complete' : '' ?>"><div class="step-number"><?= $step1OK ? '✓' : '1' ?></div><div><div class="step-title">Endereço</div><div class="step-desc">De onde você envia</div></div></div>
                <div class="step-item <?= $step2OK ? 'complete' : '' ?>"><div class="step-number"><?= $step2OK ? '✓' : '2' ?></div><div><div class="step-title">Métodos</div><div class="step-desc">Como você envia</div></div></div>
                <div class="step-item <?= $step3OK ? 'complete' : '' ?>"><div class="step-number"><?= $step3OK ? '✓' : '3' ?></div><div><div class="step-title">Preços</div><div class="step-desc">Quanto cobrar</div></div></div>
            </div>

            <!-- PASSO 1 -->
            <div class="section-card">
                <div class="section-header" onclick="toggleSection('step1')">
                    <div class="section-title"><iconify-icon icon="solar:map-point-bold"></iconify-icon><h3>Passo 1: De onde você envia?</h3></div>
                    <span class="section-badge <?= $step1OK ? 'complete' : 'pending' ?>"><?= $step1OK ? '✓ Configurado' : 'Pendente' ?></span>
                </div>
                <div class="section-body" id="step1" style="<?= $step1OK ? 'display:none;' : '' ?>">
                    <div class="guide-box"><iconify-icon icon="solar:info-circle-bold"></iconify-icon><p>Informe o CEP de onde os produtos serão enviados (seu estoque ou loja física).</p></div>
                    <form method="POST">
                        <input type="hidden" name="action" value="update_origin">
                        <div class="form-grid">
                            <div class="form-group"><label>CEP de Origem *</label><input type="text" name="origin_zipcode" class="form-control" value="<?= htmlspecialchars($store['origin_zipcode'] ?? '') ?>" placeholder="00000-000" maxlength="9" required></div>
                            <div class="form-group"><label>Cidade</label><input type="text" name="origin_city" class="form-control" value="<?= htmlspecialchars($store['origin_city'] ?? '') ?>" placeholder="Sua cidade"></div>
                            <div class="form-group"><label>Estado</label><select name="origin_state" class="form-control"><option value="">Selecione</option><?php foreach (['AC','AL','AP','AM','BA','CE','DF','ES','GO','MA','MT','MS','MG','PA','PB','PR','PE','PI','RJ','RN','RS','RO','RR','SC','SP','SE','TO'] as $uf): ?><option value="<?= $uf ?>" <?= ($store['origin_state'] ?? '') === $uf ? 'selected' : '' ?>><?= $uf ?></option><?php endforeach; ?></select></div>
                            <div class="form-group"><label>Tempo de Preparo</label><input type="number" name="handling_time" class="form-control" value="<?= intval($store['handling_time'] ?? 0) ?>" min="0"><span class="form-help">Dias para preparar antes de enviar</span></div>
                        </div>
                        <div style="margin-top: 1.25rem;"><button type="submit" class="btn-save"><iconify-icon icon="solar:diskette-bold"></iconify-icon> Salvar Endereço</button></div>
                    </form>
                </div>
            </div>

            <!-- PASSO 2 -->
            <div class="section-card">
                <div class="section-header" onclick="toggleSection('step2')">
                    <div class="section-title"><iconify-icon icon="solar:box-bold"></iconify-icon><h3>Passo 2: Como você vai enviar?</h3></div>
                    <span class="section-badge <?= $step2OK ? 'complete' : 'pending' ?>"><?= $step2OK ? count($shippingMethods) . ' método(s)' : 'Pendente' ?></span>
                </div>
                <div class="section-body" id="step2" style="<?= !$step1OK ? 'display:none;' : '' ?>">
                    <div class="guide-box"><iconify-icon icon="solar:info-circle-bold"></iconify-icon><p><strong>Opção Fácil:</strong> Conecte o <strong>Melhor Envio</strong> para calcular frete automaticamente. <strong>Opção Manual:</strong> Crie tabelas de preço por região.</p></div>
                    <div class="type-tabs">
                        <button type="button" class="type-tab active" onclick="showTab('auto')"><iconify-icon icon="solar:magic-stick-3-bold"></iconify-icon> Automático</button>
                        <button type="button" class="type-tab" onclick="showTab('manual')"><iconify-icon icon="solar:document-text-bold"></iconify-icon> Manual</button>
                    </div>

                    <div id="tab-auto">
                        <?php $meToken = $integrationsMap['melhor_envio']['api_token'] ?? null; $meConnected = isset($integrationsMap['melhor_envio']); ?>
                        <div class="integration-card <?= $meConnected ? 'connected' : '' ?>">
                            <div class="integration-header">
                                <iconify-icon icon="solar:box-bold" style="font-size:28px;color:#0ea5e9"></iconify-icon>
                                <span style="font-weight:600;">Melhor Envio</span>
                                <span class="integration-status <?= $meConnected ? 'connected' : '' ?>"><?= $meConnected ? '✓ Conectado' : 'Não conectado' ?></span>
                            </div>
                            <p style="color: var(--text-muted); font-size: 0.9rem; margin-bottom: 1rem;">Calcule frete automaticamente com <strong>Correios, Jadlog, Azul</strong> e mais.</p>
                            
                            <?php if ($meConnected): ?>
                            <!-- Estado Conectado -->
                            <div style="background: rgba(16, 185, 129, 0.08); border: 1px solid rgba(16, 185, 129, 0.3); padding: 1rem; border-radius: 10px; margin-bottom: 1rem;">
                                <div style="display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.5rem;">
                                    <iconify-icon icon="solar:check-circle-bold" style="color: #10b981;"></iconify-icon>
                                    <strong style="color: #059669;">Token Ativo</strong>
                                </div>
                                <code style="font-size: 0.8rem; color: var(--text-muted); word-break: break-all;"><?= substr($meToken, 0, 20) ?>...<?= substr($meToken, -15) ?></code>
                            </div>
                            <div style="display: flex; gap: 0.75rem; flex-wrap: wrap;">
                                <form method="POST" style="display:inline;"><input type="hidden" name="action" value="save_integration"><input type="hidden" name="provider" value="melhor_envio"><label style="display:flex;align-items:center;gap:0.5rem;cursor:pointer;padding:0.5rem 0;"><input type="checkbox" name="sandbox_mode" <?= ($integrationsMap['melhor_envio']['sandbox_mode'] ?? 0) ? 'checked' : '' ?> onchange="this.form.submit()"> Modo Sandbox</label></form>
                                <form method="POST" onsubmit="return confirm('Desconectar integração?');"><input type="hidden" name="action" value="disconnect_integration"><input type="hidden" name="provider" value="melhor_envio"><button type="submit" style="padding:0.5rem 1rem;background:rgba(239,68,68,0.1);color:#dc2626;border:1px solid rgba(239,68,68,0.3);border-radius:8px;cursor:pointer;font-weight:500;display:flex;align-items:center;gap:0.5rem;"><iconify-icon icon="solar:plug-circle-bold"></iconify-icon> Desconectar</button></form>
                            </div>
                            <?php else: ?>
                            <!-- Estado Não Conectado -->
                            <form method="POST">
                                <input type="hidden" name="action" value="save_integration">
                                <input type="hidden" name="provider" value="melhor_envio">
                                <div class="form-group" style="margin-bottom: 1rem;"><label>Token de Acesso</label><input type="password" name="api_token" class="form-control" placeholder="Cole seu token aqui" required><span class="form-help">Gere em: melhorenvio.com.br → Tokens</span></div>
                                <div style="display:flex;align-items:center;gap:1rem;flex-wrap:wrap;">
                                    <button type="submit" class="btn-save"><iconify-icon icon="solar:plug-circle-bold"></iconify-icon> Conectar</button>
                                    <label style="display:flex;align-items:center;gap:0.5rem;cursor:pointer;"><input type="checkbox" name="sandbox_mode"> Modo Sandbox</label>
                                </div>
                            </form>
                            <?php endif; ?>
                        </div>
                        <p style="text-align:center;color:var(--text-muted);font-size:0.85rem;">Não tem conta? <a href="https://melhorenvio.com.br/p/QjbtLrkiul" target="_blank" style="color:var(--primary);">Crie grátis →</a></p>
                    </div>

                    <div id="tab-manual" style="display:none;">
                        <?php if (empty($shippingMethods)): ?>
                        <div class="empty-state"><iconify-icon icon="solar:box-minimalistic-bold"></iconify-icon><p><strong>Nenhum método</strong></p><button type="button" class="btn-add" onclick="openModal('addMethodModal')" style="margin-top:1rem;"><iconify-icon icon="solar:add-circle-bold"></iconify-icon> Criar Método</button></div>
                        <?php else: ?>
                        <table class="simple-table"><thead><tr><th>Método</th><th>Status</th><th></th></tr></thead><tbody>
                        <?php foreach ($shippingMethods as $m): ?>
                        <tr><td><strong><?= htmlspecialchars($m['name']) ?></strong><span style="display:block;font-size:0.8rem;color:var(--text-muted);"><?= $m['type'] === 'free' ? 'Frete Grátis' : ($m['type'] === 'local_pickup' ? 'Retirada' : 'Tabela') ?></span></td><td style="color:<?= $m['is_active'] ? '#10b981' : '#6b7280' ?>;"><?= $m['is_active'] ? '✓ Ativo' : '○ Inativo' ?></td><td style="text-align:right;white-space:nowrap;"><button type="button" onclick="openEditMethodModal(<?= $m['id'] ?>, '<?= addslashes($m['name']) ?>', '<?= $m['type'] ?>', <?= floatval($m['min_order_value'] ?? 0) ?>)" style="background:none;border:none;cursor:pointer;color:var(--primary);padding:0.5rem;" title="Editar"><iconify-icon icon="solar:pen-bold"></iconify-icon></button><form method="POST" style="display:inline;"><input type="hidden" name="action" value="toggle_method"><input type="hidden" name="method_id" value="<?= $m['id'] ?>"><button type="submit" style="background:none;border:none;cursor:pointer;color:var(--text-muted);padding:0.5rem;" title="<?= $m['is_active'] ? 'Desativar' : 'Ativar' ?>"><iconify-icon icon="<?= $m['is_active'] ? 'solar:eye-closed-bold' : 'solar:eye-bold' ?>"></iconify-icon></button></form><form method="POST" style="display:inline;" onsubmit="return confirm('Remover método e todas as zonas?')"><input type="hidden" name="action" value="delete_method"><input type="hidden" name="method_id" value="<?= $m['id'] ?>"><button type="submit" style="background:none;border:none;cursor:pointer;color:#ef4444;padding:0.5rem;" title="Excluir"><iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon></button></form></td></tr>
                        <?php endforeach; ?>
                        </tbody></table>
                        <div style="margin-top:1rem;"><button type="button" class="btn-add" onclick="openModal('addMethodModal')"><iconify-icon icon="solar:add-circle-bold"></iconify-icon> Adicionar</button></div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- PASSO 3 -->
            <?php if (!empty($shippingMethods)): ?>
            <div class="section-card">
                <div class="section-header" onclick="toggleSection('step3')">
                    <div class="section-title"><iconify-icon icon="solar:tag-price-bold"></iconify-icon><h3>Passo 3: Preços por região</h3></div>
                    <span class="section-badge <?= $step3OK ? 'complete' : 'pending' ?>"><?= count($shippingZones) ?> zona(s)</span>
                </div>
                <div class="section-body" id="step3">
                    <div class="guide-box"><iconify-icon icon="solar:info-circle-bold"></iconify-icon><p>Defina faixas de CEP e quanto cobrar. Ex: CEPs 01000-000 a 09999-999 = R$ 15,00</p></div>
                    <?php if (empty($shippingZones)): ?>
                    <div class="empty-state"><iconify-icon icon="solar:map-minimalistic-bold"></iconify-icon><p><strong>Nenhuma zona</strong></p><button type="button" class="btn-add" onclick="openModal('addZoneModal')" style="margin-top:1rem;"><iconify-icon icon="solar:add-circle-bold"></iconify-icon> Criar Zona</button></div>
                    <?php else: ?>
                    <table class="simple-table"><thead><tr><th>Região</th><th>CEP</th><th>Preço</th><th>Prazo</th><th></th></tr></thead><tbody>
                    <?php foreach ($shippingZones as $z): ?>
                    <tr><td><strong><?= htmlspecialchars($z['name']) ?></strong><span style="display:block;font-size:0.8rem;color:var(--text-muted);"><?= htmlspecialchars($z['method_name']) ?></span></td><td style="font-family:monospace;"><?= substr($z['zipcode_start'],0,5) ?>-<?= substr($z['zipcode_start'],5) ?> a <?= substr($z['zipcode_end'],0,5) ?>-<?= substr($z['zipcode_end'],5) ?></td><td style="color:#10b981;font-weight:600;">R$ <?= number_format($z['price'], 2, ',', '.') ?></td><td><?= $z['min_days'] ?>-<?= $z['max_days'] ?> dias</td><td style="white-space:nowrap;"><button type="button" onclick="openEditZoneModal(<?= $z['id'] ?>, '<?= addslashes($z['name']) ?>', '<?= $z['zipcode_start'] ?>', '<?= $z['zipcode_end'] ?>', <?= $z['price'] ?>, <?= $z['min_days'] ?>, <?= $z['max_days'] ?>)" style="background:none;border:none;cursor:pointer;color:var(--primary);padding:0.5rem;" title="Editar"><iconify-icon icon="solar:pen-bold"></iconify-icon></button><form method="POST" style="display:inline;" onsubmit="return confirm('Remover?')"><input type="hidden" name="action" value="delete_zone"><input type="hidden" name="zone_id" value="<?= $z['id'] ?>"><button type="submit" style="background:none;border:none;cursor:pointer;color:#ef4444;padding:0.5rem;" title="Excluir"><iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon></button></form></td></tr>
                    <?php endforeach; ?>
                    </tbody></table>
                    <div style="margin-top:1rem;display:flex;gap:1rem;flex-wrap:wrap;">
                        <button type="button" class="btn-add" onclick="openModal('addZoneModal')"><iconify-icon icon="solar:add-circle-bold"></iconify-icon> Adicionar</button>
                        <button type="button" class="btn-add" onclick="openModal('csvModal')"><iconify-icon icon="solar:file-text-bold"></iconify-icon> Importar CSV</button>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </main>
</div>

<!-- Modal: Adicionar Método -->
<div id="addMethodModal" class="modal-overlay" onclick="if(event.target===this)closeModal('addMethodModal')">
    <div class="modal-box">
        <div class="modal-header"><h3>Criar Método de Envio</h3><button type="button" onclick="closeModal('addMethodModal')" class="modal-close">&times;</button></div>
        <form method="POST">
            <input type="hidden" name="action" value="add_method">
            <div class="modal-body">
                <div class="form-group" style="margin-bottom:1rem;"><label>Nome *</label><input type="text" name="method_name" class="form-control" placeholder="Ex: PAC, SEDEX, Motoboy" required></div>
                <div class="form-group" style="margin-bottom:1rem;"><label>Tipo</label><select name="method_type" class="form-control"><option value="manual">Tabela de Preços</option><option value="local_pickup">Retirada no Local</option><option value="free">Frete Grátis</option></select></div>
                <div class="form-group"><label>Frete grátis acima de R$</label><input type="number" name="min_order_value" class="form-control" step="0.01" min="0" placeholder="0 = não aplicar"></div>
            </div>
            <div class="modal-footer"><button type="button" onclick="closeModal('addMethodModal')" style="padding:0.75rem 1.25rem;background:var(--bg);border:1px solid var(--border-color);border-radius:8px;cursor:pointer;">Cancelar</button><button type="submit" class="btn-save">Criar</button></div>
        </form>
    </div>
</div>

<!-- Modal: Adicionar Zona -->

<!-- Modal: Editar Método -->
<div id="editMethodModal" class="modal-overlay" onclick="if(event.target===this)closeModal('editMethodModal')">
    <div class="modal-box">
        <div class="modal-header"><h3>Editar Método de Envio</h3><button type="button" onclick="closeModal('editMethodModal')" class="modal-close">&times;</button></div>
        <form method="POST">
            <input type="hidden" name="action" value="edit_method">
            <input type="hidden" name="method_id" id="edit_method_id">
            <div class="modal-body">
                <div class="form-group" style="margin-bottom:1rem;"><label>Nome *</label><input type="text" name="method_name" id="edit_method_name" class="form-control" required></div>
                <div class="form-group" style="margin-bottom:1rem;"><label>Tipo</label><select name="method_type" id="edit_method_type" class="form-control"><option value="manual">Tabela de Preços</option><option value="local_pickup">Retirada no Local</option><option value="free">Frete Grátis</option></select></div>
                <div class="form-group"><label>Frete grátis acima de R$</label><input type="number" name="min_order_value" id="edit_min_order_value" class="form-control" step="0.01" min="0" placeholder="0 = não aplicar"></div>
            </div>
            <div class="modal-footer"><button type="button" onclick="closeModal('editMethodModal')" style="padding:0.75rem 1.25rem;background:var(--bg);border:1px solid var(--border-color);border-radius:8px;cursor:pointer;">Cancelar</button><button type="submit" class="btn-save">Salvar</button></div>
        </form>
    </div>
</div>

<div id="addZoneModal" class="modal-overlay" onclick="if(event.target===this)closeModal('addZoneModal')">
    <div class="modal-box">
        <div class="modal-header"><h3>Criar Zona de Frete</h3><button type="button" onclick="closeModal('addZoneModal')" class="modal-close">&times;</button></div>
        <form method="POST">
            <input type="hidden" name="action" value="add_zone">
            <div class="modal-body">
                <div class="form-group" style="margin-bottom:1rem;"><label>Método *</label><select name="method_id" class="form-control" required><option value="">Selecione</option><?php foreach ($shippingMethods as $m): ?><option value="<?= $m['id'] ?>"><?= htmlspecialchars($m['name']) ?></option><?php endforeach; ?></select></div>
                <div class="form-group" style="margin-bottom:1rem;"><label>Nome da Região *</label><input type="text" name="zone_name" class="form-control" placeholder="Ex: Grande São Paulo" required></div>
                <div class="form-grid" style="margin-bottom:1rem;"><div class="form-group"><label>CEP Inicial *</label><input type="text" name="zipcode_start" class="form-control" placeholder="01000000" maxlength="8" required></div><div class="form-group"><label>CEP Final *</label><input type="text" name="zipcode_end" class="form-control" placeholder="09999999" maxlength="8" required></div></div>
                <div class="form-group" style="margin-bottom:1rem;"><label>Preço R$ *</label><input type="number" name="zone_price" class="form-control" step="0.01" min="0" placeholder="15.00" required></div>
                <div class="form-grid"><div class="form-group"><label>Dias Mín</label><input type="number" name="min_days" class="form-control" value="1" min="0"></div><div class="form-group"><label>Dias Máx</label><input type="number" name="max_days" class="form-control" value="5" min="0"></div></div>
            </div>
            <div class="modal-footer"><button type="button" onclick="closeModal('addZoneModal')" style="padding:0.75rem 1.25rem;background:var(--bg);border:1px solid var(--border-color);border-radius:8px;cursor:pointer;">Cancelar</button><button type="submit" class="btn-save">Criar</button></div>
        </form>
    </div>
</div>

<!-- Modal: CSV -->

<!-- Modal: Editar Zona -->
<div id="editZoneModal" class="modal-overlay" onclick="if(event.target===this)closeModal('editZoneModal')">
    <div class="modal-box">
        <div class="modal-header"><h3>Editar Zona de Frete</h3><button type="button" onclick="closeModal('editZoneModal')" class="modal-close">&times;</button></div>
        <form method="POST">
            <input type="hidden" name="action" value="edit_zone">
            <input type="hidden" name="zone_id" id="edit_zone_id">
            <div class="modal-body">
                <div class="form-group" style="margin-bottom:1rem;"><label>Nome da Região *</label><input type="text" name="zone_name" id="edit_zone_name" class="form-control" required></div>
                <div class="form-grid" style="margin-bottom:1rem;"><div class="form-group"><label>CEP Inicial *</label><input type="text" name="zipcode_start" id="edit_zipcode_start" class="form-control" maxlength="8" required></div><div class="form-group"><label>CEP Final *</label><input type="text" name="zipcode_end" id="edit_zipcode_end" class="form-control" maxlength="8" required></div></div>
                <div class="form-group" style="margin-bottom:1rem;"><label>Preço R$ *</label><input type="number" name="zone_price" id="edit_zone_price" class="form-control" step="0.01" min="0" required></div>
                <div class="form-grid"><div class="form-group"><label>Dias Mín</label><input type="number" name="min_days" id="edit_min_days" class="form-control" min="0"></div><div class="form-group"><label>Dias Máx</label><input type="number" name="max_days" id="edit_max_days" class="form-control" min="0"></div></div>
            </div>
            <div class="modal-footer"><button type="button" onclick="closeModal('editZoneModal')" style="padding:0.75rem 1.25rem;background:var(--bg);border:1px solid var(--border-color);border-radius:8px;cursor:pointer;">Cancelar</button><button type="submit" class="btn-save">Salvar</button></div>
        </form>
    </div>
</div>

<div id="csvModal" class="modal-overlay" onclick="if(event.target===this)closeModal('csvModal')">
    <div class="modal-box">
        <div class="modal-header"><h3>Importar via CSV</h3><button type="button" onclick="closeModal('csvModal')" class="modal-close">&times;</button></div>
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="upload_csv">
            <div class="modal-body">
                <div class="form-group" style="margin-bottom:1rem;"><label>Método *</label><select name="csv_method_id" class="form-control" required><option value="">Selecione</option><?php foreach ($shippingMethods as $m): ?><option value="<?= $m['id'] ?>"><?= htmlspecialchars($m['name']) ?></option><?php endforeach; ?></select></div>
                <div class="form-group" style="margin-bottom:1rem;"><label>Arquivo CSV *</label><input type="file" name="csv_file" class="form-control" accept=".csv" required></div>
                <div style="background:var(--bg);padding:1rem;border-radius:8px;font-size:0.85rem;"><strong>Formato:</strong><pre style="margin:0.5rem 0 0;font-family:monospace;font-size:0.8rem;">Região;CEP Início;CEP Fim;Preço;Dias Mín;Dias Máx
Grande SP;01000000;09999999;15.00;1;3</pre></div>
            </div>
            <div class="modal-footer"><button type="button" onclick="closeModal('csvModal')" style="padding:0.75rem 1.25rem;background:var(--bg);border:1px solid var(--border-color);border-radius:8px;cursor:pointer;">Cancelar</button><button type="submit" class="btn-save">Importar</button></div>
        </form>
    </div>
</div>

<script>
function toggleSection(id) { const el = document.getElementById(id); if (el) el.style.display = el.style.display === 'none' ? 'block' : 'none'; }
function openModal(id) { document.getElementById(id).classList.add('active'); }
function closeModal(id) { document.getElementById(id).classList.remove('active'); }
function openEditZoneModal(id, name, cepStart, cepEnd, price, minDays, maxDays) {
    document.getElementById('edit_zone_id').value = id;
    document.getElementById('edit_zone_name').value = name;
    document.getElementById('edit_zipcode_start').value = cepStart;
    document.getElementById('edit_zipcode_end').value = cepEnd;
    document.getElementById('edit_zone_price').value = price;
    document.getElementById('edit_min_days').value = minDays;
    document.getElementById('edit_max_days').value = maxDays;
    openModal('editZoneModal');
}
function showTab(tab) { document.querySelectorAll('.type-tab').forEach(t => t.classList.remove('active')); event.target.closest('.type-tab').classList.add('active'); document.getElementById('tab-auto').style.display = tab === 'auto' ? 'block' : 'none'; document.getElementById('tab-manual').style.display = tab === 'manual' ? 'block' : 'none'; }
function openEditMethodModal(id, name, type, minOrderValue) {
    document.getElementById('edit_method_id').value = id;
    document.getElementById('edit_method_name').value = name;
    document.getElementById('edit_method_type').value = type;
    document.getElementById('edit_min_order_value').value = minOrderValue;
    openModal('editMethodModal');
}
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
