<?php
session_start();
require_once '../config/db.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}
$user_id = $_SESSION['user_id'];

// Listar clientes para selecionar
$stmt = $pdo->prepare("SELECT * FROM client_customers WHERE user_id = ?");
$stmt->execute([$user_id]);
$clientes = $stmt->fetchAll();

// Filtros de busca
$search_cliente = $_GET['search_cliente'] ?? '';
$search_data_ini = $_GET['search_data_ini'] ?? '';
$search_data_fim = $_GET['search_data_fim'] ?? '';

// --- INÍCIO DA CORREÇÃO ---

// SQL para listar fiados cadastrados + cliente e telefone, com filtros
$sql = "
    SELECT 
        f.id, 
        cc.name as cliente, 
        cc.phone, 
        f.description, 
        f.total_amount, 
        f.saldo, 
        f.valor_pago, 
        COUNT(i.id) as num_parcelas, 
        MIN(i.due_date) as primeiro_venc
    FROM fiados f
    JOIN client_customers cc ON cc.id = f.customer_id
    LEFT JOIN installments i ON i.fiado_id = f.id
    WHERE f.user_id = ? AND f.saldo > 0
";
$params = [$user_id];

// Filtros que atuam antes do agrupamento (cláusula WHERE)
if ($search_cliente != '') {
    $sql .= " AND cc.name LIKE ? ";
    $params[] = '%' . $search_cliente . '%';
}

$sql .= " GROUP BY f.id, cc.name, cc.phone, f.description, f.total_amount, f.saldo, f.valor_pago ";

// Filtros que atuam depois do agrupamento (cláusula HAVING)
$having_clauses = [];
$having_params = [];

if ($search_data_ini != '') {
    $having_clauses[] = " MIN(i.due_date) >= ? ";
    $having_params[] = $search_data_ini;
}
if ($search_data_fim != '') {
    $having_clauses[] = " MIN(i.due_date) <= ? ";
    $having_params[] = $search_data_fim;
}

if (!empty($having_clauses)) {
    $sql .= " HAVING " . implode(' AND ', $having_clauses);
}

$sql .= " ORDER BY f.id DESC ";

// Combina os parâmetros de WHERE e HAVING na ordem correta
$final_params = array_merge($params, $having_params);

$stmt = $pdo->prepare($sql);
$stmt->execute($final_params);
$fiados = $stmt->fetchAll();

// --- NOVA FUNCIONALIDADE: CALCULAR TOTAIS ---
$total_valor_total = 0;
$total_saldo = 0;
$total_valor_pago = 0;

foreach ($fiados as $f) {
    $total_valor_total += $f['total_amount'];
    $total_saldo += $f['saldo'];
    $total_valor_pago += $f['valor_pago'];
}

// --- FIM DA CORREÇÃO ---


// Cadastro de fiado
$sucesso = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_fiado'])) {
    $customer_id = $_POST['customer_id'];
    $desc = trim($_POST['description']);
    $total = floatval($_POST['total_amount']);
    $parcelas = intval($_POST['parcelas']);
    $vencimento = $_POST['primeiro_venc'];
    // Criando registro fiado já com saldo e valor_pago
    $stmt = $pdo->prepare("INSERT INTO fiados (customer_id, user_id, description, total_amount, saldo, valor_pago) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([$customer_id, $user_id, $desc, $total, $total, 0]);
    $fiado_id = $pdo->lastInsertId();

    // Gerando parcelas
    $valor_parcela = number_format($total / $parcelas, 2, '.', '');
    for ($i = 0; $i < $parcelas; $i++) {
        $dt = date('Y-m-d', strtotime("+$i month", strtotime($vencimento)));
        $stmt = $pdo->prepare("INSERT INTO installments (fiado_id, due_date, amount) VALUES (?, ?, ?)");
        $stmt->execute([$fiado_id, $dt, $valor_parcela]);
    }
    $sucesso = true;
    header("Location: fiados.php");
    exit;
}

// Marcar parcela como paga - SISTEMA TOTALMENTE CORRIGIDO
$parcela_msg = '';
if (isset($_POST['pagar_parcela'])) {
    $parcela_id = intval($_POST['parcela_id']);
    $payment_amount = floatval($_POST['payment_amount']);

    // Pega os detalhes da parcela
    $stmt = $pdo->prepare("SELECT * FROM installments WHERE id = ?");
    $stmt->execute([$parcela_id]);
    $parcela = $stmt->fetch();
    
    if (!$parcela) {
        $parcela_msg = "Parcela não encontrada!";
    } else {
        $fiado_id = $parcela['fiado_id'];
        $remaining_amount = $parcela['amount'] - $parcela['paid_amount'];

        // Verificar se é um estorno (payment_amount = 0)
        if ($payment_amount == 0 && $parcela['status'] == 2) {
            // Estorno: zerar o valor pago e voltar status para em aberto
            $stmt = $pdo->prepare("UPDATE installments SET paid_amount = 0, status = 0 WHERE id = ?");
            $stmt->execute([$parcela_id]);
            $parcela_msg = "Pagamento estornado com sucesso!";
        } 
        // Verificar se o valor do pagamento é válido
        else if ($payment_amount > 0 && $payment_amount <= $remaining_amount) {
            $new_paid_amount = $parcela['paid_amount'] + $payment_amount;
            $new_remaining = $parcela['amount'] - $new_paid_amount;

            if ($new_remaining <= 0.01) { 
                // Parcela totalmente quitada
                $stmt = $pdo->prepare("UPDATE installments SET paid_amount = amount, status = 2 WHERE id = ?");
                $stmt->execute([$parcela_id]);
                $parcela_msg = "Parcela quitada totalmente! Valor pago: R$ " . number_format($payment_amount, 2, ',', '.');
            } else { 
                // Pagamento parcial
                $stmt = $pdo->prepare("UPDATE installments SET paid_amount = ?, status = 1 WHERE id = ?");
                $stmt->execute([$new_paid_amount, $parcela_id]);
                
                $parcela_msg = "Pagamento parcial registrado! Valor pago: R$ " . number_format($payment_amount, 2, ',', '.') . " - Restante: R$ " . number_format($new_remaining, 2, ',', '.');
            }
        } else {
            $parcela_msg = "Valor de pagamento inválido! Deve ser entre R$ 0,01 e R$ " . number_format($remaining_amount, 2, ',', '.');
        }

        // --- CORREÇÃO CRÍTICA: ATUALIZAÇÃO CORRETA DOS TOTAIS NO FIADO ---
        // Só atualiza se houve uma operação válida (pagamento ou estorno)
        if ($parcela_msg != "Parcela não encontrada!" && $parcela_msg != "Valor de pagamento inválido! Deve ser entre R$ 0,01 e R$ " . number_format($remaining_amount, 2, ',', '.')) {
            
            // Recalcular valor_pago somando todos os paid_amount das parcelas deste fiado
            $stmt = $pdo->prepare("SELECT COALESCE(SUM(paid_amount), 0) as total_pago FROM installments WHERE fiado_id = ?");
            $stmt->execute([$fiado_id]);
            $result = $stmt->fetch();
            $valor_pago_total = floatval($result['total_pago']);
            
            // Pegar o valor total do fiado
            $stmt = $pdo->prepare("SELECT total_amount FROM fiados WHERE id = ?");
            $stmt->execute([$fiado_id]);
            $total_fiado = floatval($stmt->fetchColumn());
            
            // Calcular novo saldo
            $novo_saldo = $total_fiado - $valor_pago_total;
            
            // Garantir que o saldo não seja negativo
            if ($novo_saldo < 0) {
                $novo_saldo = 0;
            }
            
            // Atualizar a tabela fiados com os valores corretos
            $stmt = $pdo->prepare("UPDATE fiados SET valor_pago = ?, saldo = ? WHERE id = ?");
            $stmt->execute([$valor_pago_total, $novo_saldo, $fiado_id]);
            
            // Debug: adicionar informação na mensagem para verificar os cálculos
            $parcela_msg .= " [Debug: Total Fiado: R$ " . number_format($total_fiado, 2, ',', '.') . 
                           " | Valor Pago Total: R$ " . number_format($valor_pago_total, 2, ',', '.') . 
                           " | Novo Saldo: R$ " . number_format($novo_saldo, 2, ',', '.') . "]";
        }
    }
}

// Buscar parcelas de um fiado para modal AJAX
if (isset($_GET['ajax_parcelas']) && isset($_GET['fiado_id'])) {
    // Retorna lista de parcelas em JSON
    $fiado_id = intval($_GET['fiado_id']);
    $stmt = $pdo->prepare("SELECT id, due_date, amount, paid_amount, status FROM installments WHERE fiado_id = ? ORDER BY due_date ASC");
    $stmt->execute([$fiado_id]);
    $parcelas = $stmt->fetchAll(PDO::FETCH_ASSOC);
    header('Content-Type: application/json');
    echo json_encode($parcelas);
    exit;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Fiados - Fiado Fácil</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <style>
        :root {
            --primary-color: #1876F2;
            --primary-dark: #1356b3;
            --primary-light: #eaf4ff;
            --secondary-color: #1bbf5c;
            --success-color: #10b981;
            --warning-color: #f59e0b;
            --danger-color: #ef4444;
            --background-color: #f8fafc;
            --surface-color: #ffffff;
            --text-primary: #1e293b;
            --text-secondary: #64748b;
            --border-color: #e2e8f0;
            --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05 );
            --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
            --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
            --shadow-xl: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);
            --gradient-primary: linear-gradient(135deg, #1876F2 0%, #1356b3 100%);
            --gradient-success: linear-gradient(135deg, #10b981 0%, #059669 100%);
            --gradient-warning: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            --gradient-background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: var(--gradient-background);
            color: var(--text-primary);
            line-height: 1.6;
            min-height: 100vh;
        }

        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            width: 280px;
            background: var(--surface-color);
            backdrop-filter: blur(20px);
            border-right: 1px solid var(--border-color);
            display: flex;
            flex-direction: column;
            z-index: 100;
            box-shadow: var(--shadow-xl);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .sidebar::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 120px;
            background: var(--gradient-primary);
            opacity: 0.05;
            border-radius: 0 0 24px 0;
        }

        .sidebar .logo {
            position: relative;
            padding: 32px 24px;
            font-size: 1.75rem;
            font-weight: 800;
            color: var(--primary-color);
            display: flex;
            align-items: center;
            gap: 12px;
            border-bottom: 1px solid var(--border-color);
        }

        .sidebar .logo i {
            font-size: 2rem;
            background: var(--gradient-primary);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .sidebar nav {
            flex: 1;
            padding: 24px 16px;
        }

        .sidebar nav a {
            display: flex;
            align-items: center;
            gap: 16px;
            color: var(--text-secondary);
            text-decoration: none;
            font-size: 0.95rem;
            font-weight: 500;
            padding: 14px 20px;
            margin: 4px 0;
            border-radius: 12px;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
        }

        .sidebar nav a::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: var(--gradient-primary);
            opacity: 0;
            transition: opacity 0.3s ease;
            border-radius: 12px;
        }

        .sidebar nav a i {
            font-size: 1.1rem;
            width: 20px;
            text-align: center;
            position: relative;
            z-index: 1;
        }

        .sidebar nav a span {
            position: relative;
            z-index: 1;
        }

        .sidebar nav a.active,
        .sidebar nav a:hover {
            color: white;
            transform: translateX(4px);
            box-shadow: var(--shadow-md);
        }

        .sidebar nav a.active::before,
        .sidebar nav a:hover::before {
            opacity: 1;
        }

        .sidebar .bottom {
            padding: 24px;
            border-top: 1px solid var(--border-color);
        }

        .sidebar .logout-link {
            display: flex;
            align-items: center;
            gap: 12px;
            color: #ef4444;
            font-weight: 600;
            font-size: 0.95rem;
            text-decoration: none;
            padding: 12px 16px;
            border-radius: 12px;
            transition: all 0.3s ease;
        }

        .sidebar .logout-link:hover {
            background: #fef2f2;
            transform: translateX(4px);
        }

        .main-content {
            margin-left: 280px;
            padding: 32px;
            min-height: 100vh;
            animation: fadeIn 0.6s ease-out;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .page-header {
            display: flex;
            align-items: center;
            gap: 16px;
            margin-bottom: 32px;
            padding-bottom: 24px;
            border-bottom: 1px solid var(--border-color);
        }

        .page-header .icon-wrapper {
            width: 56px;
            height: 56px;
            border-radius: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: var(--primary-light);
        }

        .page-header i {
            font-size: 1.75rem;
            color: var(--primary-color);
        }

        .page-header h2 {
            font-size: 2rem;
            font-weight: 700;
            color: var(--text-primary);
            margin: 0;
        }

        .success-message {
            background: var(--gradient-success);
            color: white;
            padding: 16px 20px;
            border-radius: 12px;
            margin-bottom: 24px;
            text-align: center;
            font-weight: 600;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            animation: slideDown 0.5s ease-out;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .form-card {
            background: var(--surface-color);
            border-radius: 20px;
            box-shadow: var(--shadow-md);
            padding: 32px;
            border: 1px solid var(--border-color);
            position: relative;
            overflow: hidden;
            animation: slideUp 0.6s ease-out;
            animation-delay: 0.1s;
            animation-fill-mode: both;
            margin-bottom: 32px;
        }

        .form-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--gradient-primary);
        }

        .form-card h3 {
            font-size: 1.25rem;
            font-weight: 700;
            color: var(--text-primary);
            margin-bottom: 24px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .form-card h3 i {
            color: var(--primary-color);
        }

        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .form-flex {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 24px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-card label {
            font-weight: 600;
            color: var(--text-primary);
            font-size: 0.95rem;
            margin-bottom: 8px;
        }

        .form-card select,
        .form-card input[type="text"],
        .form-card input[type="number"],
        .form-card input[type="date"] {
            width: 100%;
            padding: 14px 16px;
            border-radius: 12px;
            border: 2px solid var(--border-color);
            background: var(--surface-color);
            font-size: 1rem;
            font-family: inherit;
            outline: none;
            transition: all 0.3s ease;
        }

        .form-card select:focus,
        .form-card input:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(24, 118, 242, 0.1);
        }

        .form-card select option {
            padding: 8px;
        }

        .submit-btn {
            background: var(--gradient-primary);
            color: white;
            font-weight: 600;
            font-size: 1rem;
            border: none;
            border-radius: 12px;
            padding: 16px 32px;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            position: relative;
            overflow: hidden;
            min-width: 200px;
        }

        .submit-btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
            transition: left 0.5s;
        }

        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-lg);
        }

        .submit-btn:hover::before {
            left: 100%;
        }

        .fiados-section {
            background: var(--surface-color);
            border-radius: 20px;
            box-shadow: var(--shadow-md);
            border: 1px solid var(--border-color);
            overflow: hidden;
            animation: slideUp 0.6s ease-out;
            animation-delay: 0.2s;
            animation-fill-mode: both;
            position: relative;
        }

        .fiados-section::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--gradient-primary);
        }

        .section-header {
            padding: 24px 32px;
            border-bottom: 1px solid var(--border-color);
            background: var(--primary-light);
        }

        .section-header h3 {
            font-size: 1.25rem;
            font-weight: 700;
            color: var(--primary-color);
            margin: 0 0 20px 0;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .search-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 16px;
            align-items: end;
        }

        .search-group {
            display: flex;
            flex-direction: column;
        }

        .search-row label {
            font-size: 0.9rem;
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 6px;
        }

        .search-row input,
        .search-row select {
            padding: 10px 12px;
            border-radius: 8px;
            border: 2px solid var(--border-color);
            background: var(--surface-color);
            font-size: 0.95rem;
            outline: none;
            transition: all 0.3s ease;
        }

        .search-row input:focus,
        .search-row select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(24, 118, 242, 0.1);
        }

        .search-btn {
            background: var(--gradient-primary);
            color: white;
            font-weight: 600;
            font-size: 0.95rem;
            border: none;
            border-radius: 8px;
            padding: 10px 20px;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
            justify-content: center;
        }

        .search-btn:hover {
            transform: translateY(-1px);
            box-shadow: var(--shadow-md);
        }

        .table-container {
            padding: 24px 32px;
            overflow-x: auto;
        }

        .fiados-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 800px;
        }

        .fiados-table th {
            background: var(--surface-color);
            color: var(--text-primary);
            font-size: 0.9rem;
            font-weight: 600;
            padding: 16px 12px;
            text-align: left;
            border-bottom: 2px solid var(--border-color);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .fiados-table td {
            font-size: 0.95rem;
            color: var(--text-primary);
            padding: 16px 12px;
            border-bottom: 1px solid var(--border-color);
            transition: all 0.3s ease;
        }

        .fiados-table tbody tr:hover td {
            background: var(--primary-light);
        }

        .fiados-table tr:last-child td {
            border-bottom: none;
        }

        /* NOVA CLASSE PARA LINHA DE TOTAIS */
        .totals-row {
            background: var(--primary-light) !important;
            font-weight: 700 !important;
            color: var(--primary-color) !important;
            border-top: 3px solid var(--primary-color) !important;
        }

        .totals-row td {
            background: var(--primary-light) !important;
            font-weight: 700 !important;
            color: var(--primary-color) !important;
            font-size: 1rem !important;
        }

        .actions-cell {
            display: flex;
            gap: 8px;
            align-items: center;
            flex-wrap: wrap;
        }

        .btn-action {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 8px 12px;
            border-radius: 8px;
            font-size: 0.85rem;
            font-weight: 600;
            text-decoration: none;
            border: none;
            cursor: pointer;
            transition: all 0.3s ease;
            white-space: nowrap;
        }

        .btn-carne {
            background: var(--gradient-primary);
            color: white;
        }

        .btn-carne:hover {
            transform: translateY(-1px);
            box-shadow: var(--shadow-md);
        }

        .btn-whatsapp {
            background: #25D366;
            color: white;
        }

        .btn-whatsapp:hover {
            background: #128C7E;
            transform: translateY(-1px);
            box-shadow: var(--shadow-md);
        }

        .btn-pagar {
            background: var(--gradient-warning);
            color: white;
        }

        .btn-pagar:hover {
            transform: translateY(-1px);
            box-shadow: var(--shadow-md);
        }

        /* Modal */
        .modal-bg {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1200;
            justify-content: center;
            align-items: center;
            backdrop-filter: blur(4px);
        }

        .modal-bg.active {
            display: flex;
            animation: fadeIn 0.3s ease-out;
        }

        .modal {
            background: var(--surface-color);
            padding: 32px;
            border-radius: 20px;
            box-shadow: var(--shadow-xl);
            min-width: 400px;
            max-width: 90vw;
            max-height: 80vh;
            overflow-y: auto;
            position: relative;
            animation: modalSlideIn 0.3s ease-out;
        }

        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: scale(0.9) translateY(-20px);
            }
            to {
                opacity: 1;
                transform: scale(1) translateY(0);
            }
        }

        .modal h3 {
            margin: 0 0 24px 0;
            font-size: 1.5rem;
            color: var(--primary-color);
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .modal .close-btn {
            position: absolute;
            top: 20px;
            right: 20px;
            background: transparent;
            border: none;
            font-size: 1.5rem;
            color: var(--text-secondary);
            cursor: pointer;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }

        .modal .close-btn:hover {
            background: var(--border-color);
            color: var(--text-primary);
        }

        .modal table {
            width: 100%;
            border-collapse: collapse;
        }

        .modal th,
        .modal td {
            padding: 12px 8px;
            text-align: left;
            border-bottom: 1px solid var(--border-color);
        }

        .modal th {
            background: var(--primary-light);
            color: var(--primary-color);
            font-weight: 600;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .modal tr:last-child td {
            border-bottom: none;
        }

        .modal .paid {
            color: var(--success-color);
            font-weight: 600;
        }

        .modal .notpaid {
            color: var(--danger-color);
            font-weight: 600;
        }

        .modal .partial {
            color: var(--warning-color);
            font-weight: 600;
        }

        .modal .input-pagamento {
            width: 100px;
            padding: 6px 8px;
            border-radius: 8px;
            border: 1px solid var(--border-color);
            font-size: 0.9rem;
            text-align: right;
        }

        .modal .btn-pagar {
            padding: 6px 12px;
            font-size: 0.85rem;
        }

        .modal .btn-estornar {
            background: var(--border-color);
            color: var(--text-secondary);
        }

        .modal .btn-estornar:hover {
            background: var(--text-secondary);
            color: white;
        }

        /* Menu toggle para mobile */
        .menu-toggle {
            display: none;
            position: fixed;
            top: 20px;
            left: 20px;
            z-index: 1001;
            background: var(--surface-color);
            border: 2px solid var(--border-color);
            border-radius: 12px;
            padding: 12px;
            cursor: pointer;
            box-shadow: var(--shadow-md);
            color: var(--primary-color);
            font-size: 1.2rem;
        }

        /* Overlay para mobile */
        .overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 999;
        }

        /* Responsividade */
        @media (max-width: 768px) {
            .menu-toggle {
                display: block;
            }

            .overlay.active {
                display: block;
            }

            .sidebar {
                position: fixed;
                transform: translateX(-100%);
                width: 100%;
                max-width: 320px;
                z-index: 1000;
            }

            .sidebar.open {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
                padding: 20px 16px;
            }

            .page-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 12px;
            }

            .page-header h2 {
                font-size: 1.5rem;
            }

            .form-card,
            .fiados-section {
                padding: 24px;
            }

            .section-header {
                padding: 20px 24px;
            }

            .table-container {
                padding: 20px 24px;
            }

            .actions-cell {
                flex-direction: column;
                align-items: flex-start;
                gap: 6px;
            }

            .btn-action {
                font-size: 0.8rem;
                padding: 6px 10px;
            }

            .modal {
                min-width: 300px;
                padding: 24px;
            }
        }
    </style>
</head>
<body>
    <button class="menu-toggle" id="menuToggle">
        <i class="fa-solid fa-bars"></i>
    </button>
    
    <div class="overlay" id="overlay"></div>
    
    <aside class="sidebar" id="sidebar">
        <div class="logo">
            <i class="fa-solid fa-wallet"></i>
            <span>Fiado Fácil</span>
        </div>
        <nav>
            <a href="dashboard.php">
                <i class="fa-solid fa-house"></i>
                <span>Painel</span>
            </a>
            <a href="clientes.php">
                <i class="fa-solid fa-users"></i>
                <span>Clientes</span>
            </a>
            <a href="fiados.php" class="active">
                <i class="fa-solid fa-file-invoice-dollar"></i>
                <span>Fiados</span>
            </a>
            <a href="carne.php">
                <i class="fa-solid fa-file-pdf"></i>
                <span>Carnê PDF</span>
            </a>
            <a href="relatorios.php">
                <i class="fa-solid fa-chart-line"></i>
                <span>Relatórios</span>
            </a>
            <a href="configuracao.php">
                <i class="fa-solid fa-cog"></i>
                <span>Configuração</span>
            </a>
        </nav>
        <div class="bottom">
            <a href="logout.php" class="logout-link">
                <i class="fa-solid fa-right-from-bracket"></i>
                <span>Sair</span>
            </a>
        </div>
    </aside>
    
    <div class="main-content">
        <div class="page-header">
            <div class="icon-wrapper">
                <i class="fa-solid fa-file-invoice-dollar"></i>
            </div>
            <h2>Registrar Fiado</h2>
        </div>
        
        <?php if ($parcela_msg): ?>
            <div class="success-message">
                <i class="fa-solid fa-check-circle"></i>
                <?=htmlspecialchars($parcela_msg)?>
            </div>
        <?php endif; ?>
        
        <div class="form-card">
            <h3>
                <i class="fa-solid fa-plus-circle"></i>
                Novo Fiado
            </h3>
            
            <form method="post" autocomplete="off">
                <input type="hidden" name="save_fiado" value="1">
                <div class="form-flex">
                    <div class="form-group">
                        <label for="customer_id">Cliente</label>
                        <select name="customer_id" id="customer_id" required>
                            <option value="">Selecione um cliente</option>
                            <?php foreach ($clientes as $c): ?>
                                <option value="<?=$c['id']?>"><?=htmlspecialchars($c['name'])?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="description">Descrição</label>
                        <input type="text" name="description" id="description" placeholder="Descrição do fiado" required>
                    </div>
                    <div class="form-group">
                        <label for="total_amount">Valor Total</label>
                        <input type="number" name="total_amount" id="total_amount" step="0.01" placeholder="0,00" required>
                    </div>
                    <div class="form-group">
                        <label for="parcelas">Número de Parcelas</label>
                        <input type="number" name="parcelas" id="parcelas" value="1" min="1" required>
                    </div>
                    <div class="form-group">
                        <label for="primeiro_venc">Primeiro Vencimento</label>
                        <input type="date" name="primeiro_venc" id="primeiro_venc" required>
                    </div>
                </div>
                <button type="submit" class="submit-btn">
                    <i class="fa-solid fa-save"></i>
                    Salvar Fiado
                </button>
            </form>
        </div>
        
        <section class="fiados-section">
            <div class="section-header">
                <h3>
                    <i class="fa-solid fa-list"></i>
                    Lista de Fiados
                </h3>
                <form method="get" class="search-row">
                    <div class="search-group">
                        <label for="search_cliente">Cliente</label>
                        <input type="text" id="search_cliente" name="search_cliente" value="<?=htmlspecialchars($search_cliente)?>" placeholder="Nome do cliente">
                    </div>
                    <div class="search-group">
                        <label for="search_data_ini">Data Início</label>
                        <input type="date" id="search_data_ini" name="search_data_ini" value="<?=htmlspecialchars($search_data_ini)?>">
                    </div>
                    <div class="search-group">
                        <label for="search_data_fim">Data Fim</label>
                        <input type="date" id="search_data_fim" name="search_data_fim" value="<?=htmlspecialchars($search_data_fim)?>">
                    </div>
                    <div class="search-group">
                        <button type="submit" class="search-btn">
                            <i class="fa-solid fa-search"></i>
                            Buscar
                        </button>
                    </div>
                </form>
            </div>
            
            <div class="table-container">
                <table class="fiados-table">
                    <thead>
                        <tr>
                            <th>Cliente</th>
                            <th>Descrição</th>
                            <th>Valor Total</th>
                            <th>Saldo</th>
                            <th>Valor Pago</th>
                            <th>Parcelas</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if (count($fiados) > 0): ?>
                        <?php foreach ($fiados as $f): ?>
                        <tr>
                            <td><?=htmlspecialchars($f['cliente'])?></td>
                            <td><?=htmlspecialchars($f['description'])?></td>
                            <td>R$ <?=number_format($f['total_amount'],2,',','.')?></td>
                            <td>R$ <?=number_format($f['saldo'],2,',','.')?></td>
                            <td>R$ <?=number_format($f['valor_pago'],2,',','.')?></td>
                            <td><?=$f['num_parcelas']?></td>
                            <td>
                                <div class="actions-cell">
                                    <a href="carne.php?fiado_id=<?=$f['id']?>" class="btn-action btn-carne" title="Visualizar Carnê" target="_blank">
                                        <i class="fa-solid fa-file-pdf"></i> Carnê
                                    </a>
                                    <?php if (!empty($f['phone'])):
                                        $zap_msg = urlencode("Olá ". $f['cliente'].", segue o carnê da sua dívida: https://".$_SERVER['HTTP_HOST']."/public/carne.php?fiado_id=".$f['id'] );
                                        $zap_link = "https://wa.me/55".preg_replace('/\D/','',$f['phone'] )."?text=".$zap_msg;
                                    ?>
                                    <a href="<?=$zap_link?>" class="btn-action btn-whatsapp" title="Enviar pelo WhatsApp" target="_blank">
                                        <i class="fa-brands fa-whatsapp"></i> WhatsApp
                                    </a>
                                    <?php endif; ?>
                                    <button class="btn-action btn-pagar" type="button" onclick="abrirModalParcelas(<?=$f['id']?>)">
                                        <i class="fa-solid fa-check-circle"></i> Parcelas
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        
                        <!-- NOVA LINHA DE TOTAIS -->
                        <tr class="totals-row">
                            <td><strong>TOTAIS</strong></td>
                            <td>-</td>
                            <td><strong>R$ <?=number_format($total_valor_total,2,',','.')?></strong></td>
                            <td><strong>R$ <?=number_format($total_saldo,2,',','.')?></strong></td>
                            <td><strong>R$ <?=number_format($total_valor_pago,2,',','.')?></strong></td>
                            <td>-</td>
                            <td>-</td>
                        </tr>
                        
                    <?php else: ?>
                        <tr>
                            <td colspan="7" style="text-align: center; padding: 40px; color: var(--text-secondary);">
                                <i class="fa-solid fa-file-invoice-dollar" style="font-size: 2rem; margin-bottom: 16px; display: block;"></i>
                                Nenhum fiado cadastrado
                            </td>
                        </tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>
    </div>
    
    <!-- Modal de Parcelas -->
    <div class="modal-bg" id="modalParcelasBg">
        <div class="modal" id="modalParcelas">
            <button class="close-btn" onclick="fecharModalParcelas()">
                <i class="fa-solid fa-times"></i>
            </button>
            <h3>
                <i class="fa-solid fa-calendar-check"></i>
                Gerenciar Parcelas
            </h3>
            <table>
                <thead>
                    <tr>
                        <th>Vencimento</th>
                        <th>Valor</th>
                        <th>Status</th>
                        <th>Valor Restante</th>
                        <th>Ação</th>
                    </tr>
                </thead>
                <tbody id="parcelas-list">
                    <tr>
                        <td colspan="5" style="text-align:center; padding: 20px;">Carregando...</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    
    <script>
        // Menu mobile
        const menuToggle = document.getElementById('menuToggle');
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('overlay');

        menuToggle.addEventListener('click', function() {
            sidebar.classList.toggle('open');
            overlay.classList.toggle('active');
        });

        overlay.addEventListener('click', function() {
            sidebar.classList.remove('open');
            overlay.classList.remove('active');
        });

        // Fechar menu ao clicar em um link (mobile)
        const sidebarLinks = sidebar.querySelectorAll('nav a, .logout-link');
        sidebarLinks.forEach(link => {
            link.addEventListener('click', function() {
                if (window.innerWidth <= 768) {
                    sidebar.classList.remove('open');
                    overlay.classList.remove('active');
                }
            });
        });

        // Modal de parcelas
        function abrirModalParcelas(fiadoId) {
            document.getElementById('modalParcelasBg').classList.add('active');
            const tbody = document.getElementById('parcelas-list');
            tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; padding: 20px;">Carregando...</td></tr>';
            
            fetch('fiados.php?ajax_parcelas=1&fiado_id=' + fiadoId)
                .then(r => r.json())
                .then(parcelas => {
                    if(parcelas.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; padding: 20px;">Nenhuma parcela encontrada.</td></tr>';
                        return;
                    }
                    tbody.innerHTML = '';
                    parcelas.forEach(p => {
                        let statusText = '';
                        let statusClass = '';
                        if (p.status == 2) {
                            statusText = 'Pago';
                            statusClass = 'paid';
                        } else if (p.status == 1) {
                            statusText = 'Parcial';
                            statusClass = 'partial';
                        } else {
                            statusText = 'Em aberto';
                            statusClass = 'notpaid';
                        }

                        const dataVencimento = new Date(p.due_date + 'T00:00:00');
                        const dataFormatada = dataVencimento.toLocaleDateString('pt-BR');
                        const valorRestante = parseFloat(p.amount) - parseFloat(p.paid_amount);

                        let acaoHtml = '';
                        if (p.status != 2) { // Se não estiver totalmente paga
                            acaoHtml = `
                                <form method="post" style="margin:0; display:flex; align-items:center; gap: 5px;">
                                    <input type="hidden" name="parcela_id" value="${p.id}">
                                    <input type="number" name="payment_amount" step="0.01" min="0.01" max="${valorRestante.toFixed(2)}" value="${valorRestante.toFixed(2)}" class="input-pagamento">
                                    <button type="submit" name="pagar_parcela" class="btn-action btn-pagar"><i class="fa-solid fa-check"></i> Pagar</button>
                                </form>
                            `;
                        } else { // Se estiver totalmente paga
                            acaoHtml = `<form method="post" style="margin:0;"><input type="hidden" name="parcela_id" value="${p.id}"><input type="hidden" name="payment_amount" value="0"><button type="submit" name="pagar_parcela" class="btn-action btn-estornar"><i class="fa-solid fa-undo"></i> Estornar</button></form>`;
                        }

                        tbody.innerHTML += `<tr>
                            <td>${dataFormatada}</td>
                            <td>R$ ${parseFloat(p.amount).toLocaleString('pt-BR',{minimumFractionDigits:2})}</td>
                            <td><span class="${statusClass}"><i class="fa-solid fa-circle"></i> ${statusText}</span></td>
                            <td>R$ ${valorRestante.toLocaleString('pt-BR',{minimumFractionDigits:2})}</td>
                            <td>${acaoHtml}</td>
                        </tr>`;
                    });
                })
                .catch(error => {
                    tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; padding: 20px; color: var(--danger-color);">Erro ao carregar parcelas.</td></tr>';
                    console.error('Erro no fetch:', error);
                });
        }

        function fecharModalParcelas() {
            document.getElementById('modalParcelasBg').classList.remove('active');
        }

        // Fecha modal ao clicar fora
        document.getElementById('modalParcelasBg').addEventListener('click', function(e){
            if(e.target === this) fecharModalParcelas();
        });

        // Animações de entrada
        window.addEventListener('load', function() {
            document.body.style.opacity = '1';
        });

        // Definir data padrão para primeiro vencimento (próximo mês)
        document.addEventListener('DOMContentLoaded', function() {
            const hoje = new Date();
            const proximoMes = new Date(hoje.getFullYear(), hoje.getMonth() + 1, hoje.getDate());
            document.getElementById('primeiro_venc').value = proximoMes.toISOString().split('T')[0];
        });
    </script>
</body>
</html>