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

$pdo = get_db_connection();

// Filtros
$filter_unit = $_GET['unit_id'] ?? '';
$filter_status = $_GET['status'] ?? '';
$filter_days = $_GET['days'] ?? '30'; // Padrão 30 dias

$sql = "SELECT c.*, u.name as unit_name 
        FROM contracts c 
        JOIN units u ON c.unit_id = u.id 
        WHERE 1=1";
$params = [];

// Filtro por Status
if ($filter_status) {
    if ($filter_status === 'expired') {
        $sql .= " AND c.end_date < CURDATE() AND c.status NOT IN ('completed', 'canceled')";
    } else if ($filter_status === 'active_expiring') {
        $sql .= " AND c.status = 'active' AND c.end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)";
    } else {
        $sql .= " AND c.status = ?";
        $params[] = $filter_status;
    }
}

// Filtro por Unidade
if ($filter_unit) {
    $sql .= " AND c.unit_id = ?";
    $params[] = $filter_unit;
}

// Lógica de "A Vencer" (se não for 'all' e não for 'expired' ou 'active_expiring' que já tratam a data)
if ($filter_days !== 'all' && $filter_status !== 'expired' && $filter_status !== 'active_expiring') {
    $sql .= " AND c.end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL ? DAY)";
    $params[] = (int)$filter_days;
} else if ($filter_days === 'all' && $filter_status !== 'expired' && $filter_status !== 'active_expiring') {
    $sql .= " AND c.end_date >= CURDATE()";
}

$sql .= " ORDER BY c.end_date ASC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$contracts = $stmt->fetchAll();

// Lógica de Exportação
if (isset($_GET['export'])) {
    $export_type = $_GET['export'];
    if ($export_type === 'csv') {
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=relatorio_contratos_' . date('Y-m-d') . '.csv');
        $output = fopen('php://output', 'w');
        fputcsv($output, ['Vencimento', 'Título', 'Nº Contrato', 'Fornecedor', 'Unidade', 'Valor', 'Status']);

        foreach ($contracts as $contract) {
            fputcsv($output, [
                date('d/m/Y', strtotime($contract['end_date'])),
                $contract['title'],
                $contract['contract_number'],
                $contract['supplier'],
                $contract['unit_name'],
                number_format($contract['value'], 2, ',', '.'),
                ucfirst($contract['status'])
            ]);
        }
        fclose($output);
        exit;
    }
    // A exportação para PDF será adicionada em um passo futuro com uma biblioteca como FPDF ou Dompdf
}

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

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

<div class="container-fluid">
    <h2 class="mb-4">Relatório de Contratos a Vencer</h2>

    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" class="row g-3 align-items-end">
                <div class="col-md-3">
                    <label class="form-label">Unidade</label>
                    <select name="unit_id" class="form-select">
                        <option value="">Todas</option>
                        <?php foreach ($units as $unit): ?>
                            <option value="<?= $unit['id'] ?>" <?= $filter_unit == $unit['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($unit['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Status</label>
                    <select name="status" class="form-select">
                        <option value="">Todos</option>
                        <option value="active" <?= $filter_status == 'active' ? 'selected' : '' ?>>Ativo</option>
                        <option value="renewing" <?= $filter_status == 'renewing' ? 'selected' : '' ?>>Em Renovação</option>
                        <option value="draft" <?= $filter_status == 'draft' ? 'selected' : '' ?>>Rascunho</option>
                        <option value="completed" <?= $filter_status == 'completed' ? 'selected' : '' ?>>Concluído</option>
                        <option value="canceled" <?= $filter_status == 'canceled' ? 'selected' : '' ?>>Cancelado</option>
                        <option value="expired" <?= $filter_status == 'expired' ? 'selected' : '' ?>>Vencido</option>
                        <option value="active_expiring" <?= $filter_status == 'active_expiring' ? 'selected' : '' ?>>Ativos a Vencer (30d)</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Prazo de Vencimento</label>
                    <select name="days" class="form-select">
                        <option value="7" <?= $filter_days == '7' ? 'selected' : '' ?>>Próximos 7 dias</option>
                        <option value="15" <?= $filter_days == '15' ? 'selected' : '' ?>>Próximos 15 dias</option>
                        <option value="30" <?= $filter_days == '30' ? 'selected' : '' ?>>Próximos 30 dias</option>
                        <option value="60" <?= $filter_days == '60' ? 'selected' : '' ?>>Próximos 60 dias</option>
                        <option value="90" <?= $filter_days == '90' ? 'selected' : '' ?>>Próximos 90 dias</option>
                        <option value="all" <?= $filter_days == 'all' ? 'selected' : '' ?>>Todos os futuros</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-filter"></i> Filtrar</button>
                    <a href="reports.php" class="btn btn-secondary">Limpar</a>
                    <button type="submit" name="export" value="csv" class="btn btn-success"><i class="fas fa-file-csv"></i> CSV</button>
                    <button type="submit" name="export" value="pdf" class="btn btn-danger"><i class="fas fa-file-pdf"></i> PDF</button>
                </div>
            </form>
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead class="table-dark">
                        <tr>
                            <th>Vencimento</th>
                            <th>Título</th>
                            <th>Fornecedor</th>
                            <th>Unidade</th>
                            <th>Valor</th>
                            <th>Dias Restantes</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($contracts)): ?>
                            <tr>
                                <td colspan="6" class="text-center py-4 text-muted">Nenhum contrato a vencer encontrado no período selecionado.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($contracts as $contract): 
                                $days_left = floor((strtotime($contract['end_date']) - time()) / (60 * 60 * 24)) + 1;
                            ?>
                            <tr>
                                <td class="fw-bold text-danger"><?= date('d/m/Y', strtotime($contract['end_date'])) ?></td>
                                <td><?= htmlspecialchars($contract['title']) ?></td>
                                <td><?= htmlspecialchars($contract['supplier']) ?></td>
                                <td><?= htmlspecialchars($contract['unit_name']) ?></td>
                                <td>R$ <?= number_format($contract['value'], 2, ',', '.') ?></td>
                                <td>
                                    <span class="badge bg-<?= $days_left <= 7 ? 'danger' : ($days_left <= 15 ? 'warning' : 'info') ?>">
                                        <?= $days_left ?> dias
                                    </span>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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