<?php
require_once(dirname(__DIR__) . '/config/db.php');
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$empresaId = $_SESSION['empresa']['id'] ?? null;
if (!$empresaId) {
    echo "<div class='alert alert-danger'>Nenhuma empresa selecionada. Faça login novamente.</div>";
    exit;
}
?>

<h4 class="mb-3"><i class="bi bi-calendar3"></i> Exercícios Orçamentários</h4>
<hr>

<div class="d-flex justify-content-between align-items-center mb-3">
  <div class="btn-group" role="group">
    <button class="btn btn-outline-success btn-sm filtro" data-status="ativas">Ativos</button>
    <button class="btn btn-outline-secondary btn-sm filtro" data-status="inativas">Inativos</button>
    <button class="btn btn-outline-dark btn-sm filtro" data-status="todas">Todos</button>
  </div>

  <div class="d-flex align-items-center gap-2">
    <div class="input-group input-group-sm">
      <input class="form-control" id="busca" placeholder="Pesquisar exercício...">
      <button class="btn btn-outline-secondary" id="btnBuscar"><i class="bi bi-search"></i></button>
    </div>

    <select class="form-select form-select-sm w-auto" id="limit">
      <option value="50">50</option>
      <option value="100" selected>100</option>
      <option value="200">200</option>
    </select>

    <button class="btn btn-outline-light btn-sm border-secondary text-dark bg-light" id="btnNovo">
      <i class="bi bi-plus-circle"></i> Novo Exercício
    </button>
  </div>
</div>

<div class="table-responsive">
  <table class="table table-striped table-hover align-middle">
    <thead class="table-dark">
      <tr>
        <th role="button" class="ordenar" data-col="cdexercicio">#</th>
        <th role="button" class="ordenar" data-col="anoref">Ano</th>
        <th role="button" class="ordenar" data-col="descricao">Descrição</th>
        <th role="button" class="ordenar" data-col="floficial">Oficial</th>
        <th>Status</th>
        <th class="text-center">Ações</th>
      </tr>
    </thead>
    <tbody id="tbodyExercicios">
      <tr><td colspan="6" class="text-center text-muted">Carregando...</td></tr>
    </tbody>
  </table>
</div>

<!-- Modal Exercício -->
<div class="modal fade" id="modalExercicio" tabindex="-1">
  <div class="modal-dialog">
    <form class="modal-content" id="formExercicio">
      <div class="modal-header">
        <h5 class="modal-title">Cadastrar Exercício</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" id="cdexercicio">
        <div class="mb-3">
          <label class="form-label">Ano *</label>
          <input type="number" class="form-control" id="anoref" required>
        </div>
        <div class="mb-3">
          <label class="form-label">Descrição *</label>
          <input type="text" class="form-control" id="descricao" required>
        </div>
        <div class="form-check mb-3">
          <input class="form-check-input" type="checkbox" id="floficial" value="1">
          <label class="form-check-label" for="floficial">Tornar este exercício oficial</label>
        </div>
      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-success">Salvar</button>
      </div>
    </form>
  </div>
</div>

<!-- Modal Períodos -->
<div class="modal fade" id="modalPeriodos" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="periodosTitulo">Períodos do Exercício</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div id="periodosContainer" class="row g-2"></div>
        <small class="text-muted d-block mt-2">Verde = mês aberto para lançamentos / Cinza = mês fechado.</small>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fechar</button>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
const state = {
  status: 'ativas',
  order: 'anoref',
  dir: 'desc',
  busca: '',
  limit: 100,
};

const modalExercicio = new bootstrap.Modal(document.getElementById('modalExercicio'));
const modalPeriodos  = new bootstrap.Modal(document.getElementById('modalPeriodos'));
const cacheExercicios = new Map();

document.querySelectorAll('.filtro').forEach(btn => {
  btn.addEventListener('click', () => {
    document.querySelectorAll('.filtro').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    state.status = btn.dataset.status;
    carregarLista();
  });
});

document.querySelectorAll('.ordenar').forEach(th => {
  th.addEventListener('click', () => {
    const col = th.dataset.col;
    if (state.order === col) {
      state.dir = state.dir === 'asc' ? 'desc' : 'asc';
    } else {
      state.order = col;
      state.dir = 'asc';
    }
    carregarLista();
  });
});

document.getElementById('btnBuscar').addEventListener('click', () => {
  state.busca = document.getElementById('busca').value.trim();
  carregarLista();
});

document.getElementById('limit').addEventListener('change', (e) => {
  state.limit = parseInt(e.target.value, 10) || 100;
  carregarLista();
});

document.getElementById('btnNovo').addEventListener('click', () => {
  document.getElementById('cdexercicio').value = '';
  document.getElementById('anoref').value = '';
  document.getElementById('descricao').value = '';
  document.getElementById('floficial').checked = false;
  modalExercicio.show();
});

document.getElementById('formExercicio').addEventListener('submit', async (e) => {
  e.preventDefault();
  const payload = {
    cdexercicio: document.getElementById('cdexercicio').value || null,
    anoref: parseInt(document.getElementById('anoref').value, 10),
    descricao: document.getElementById('descricao').value.trim(),
    floficial: document.getElementById('floficial').checked,
  };
  const resp = await fetch('?m=exercicios_actions&ajax=salvar', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload)
  }).then(r => r.json());
  alert(resp.msg || 'Operação concluída');
  if (resp.ok) {
    modalExercicio.hide();
    carregarLista();
  }
});

async function carregarLista() {
  const params = new URLSearchParams({
    status: state.status,
    order: state.order,
    dir: state.dir,
    busca: state.busca,
    limit: state.limit
  });
  const tbody = document.getElementById('tbodyExercicios');
  tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">Carregando...</td></tr>';
  try {
    const ret = await fetch(`?m=exercicios_actions&ajax=listar&${params.toString()}`).then(r => r.json());
    if (!ret.ok) throw new Error(ret.msg || 'Erro ao listar');
    const lista = ret.data || [];
    cacheExercicios.clear();
    lista.forEach(e => cacheExercicios.set(parseInt(e.cdexercicio, 10), e));
    renderTabela(lista);
  } catch (err) {
    tbody.innerHTML = `<tr><td colspan="6" class="text-danger text-center">${err.message}</td></tr>`;
  }
}

function renderTabela(lista) {
  const tbody = document.getElementById('tbodyExercicios');
  if (!Array.isArray(lista) || lista.length === 0) {
    tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">Nenhum exercício encontrado.</td></tr>';
    return;
  }
  const filtrada = lista.filter(e => {
    if (state.status === 'ativas') return e.flativo == 0;
    if (state.status === 'inativas') return e.flativo != 0;
    return true; // todas
  });

  if (filtrada.length === 0) {
    tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">Nenhum exercício para o filtro selecionado.</td></tr>';
    return;
  }

  tbody.innerHTML = filtrada.map(e => {
    const badgeOficial = e.floficial ? '<span class="badge bg-warning text-dark">Oficial</span>' : '<span class="badge bg-secondary">Planejamento</span>';
    const badgeStatus  = e.flativo == 0 ? '<span class="badge bg-success">Ativo</span>' : '<span class="badge bg-secondary">Inativo</span>';
    const descEsc = (e.descricao || '').replace(/"/g, '&quot;');
    return `
      <tr data-id="${e.cdexercicio}" data-anoref="${e.anoref}" data-descricao="${descEsc}" data-floficial="${e.floficial}" data-flativo="${e.flativo}">
        <td>${e.cdexercicio}</td>
        <td>${e.anoref}</td>
        <td>${e.descricao}</td>
        <td>${badgeOficial}</td>
        <td>${badgeStatus}</td>
        <td class="text-center">
          <div class="btn-group btn-group-sm" role="group">
            <button class="btn btn-outline-secondary btn-edit"><i class="bi bi-pencil"></i></button>
            <button class="btn btn-outline-info btn-periodos" title="Abrir/Fechar meses"><i class="bi bi-calendar-range"></i></button>
            <button class="btn btn-outline-warning btn-oficial"><i class="bi bi-star"></i></button>
            <button class="btn btn-outline-danger btn-del" title="Excluir exercício"><i class="bi bi-trash"></i></button>
          </div>
        </td>
      </tr>`;
  }).join('');

  tbody.querySelectorAll('.btn-edit').forEach(btn => {
    btn.addEventListener('click', () => {
      const tr = btn.closest('tr');
      const e = {
        cdexercicio: tr.dataset.id,
        anoref: tr.dataset.anoref,
        descricao: tr.dataset.descricao,
        floficial: tr.dataset.floficial
      };
      editar(e);
    });
  });

  tbody.querySelectorAll('.btn-oficial').forEach(btn => {
    btn.addEventListener('click', () => {
      const tr = btn.closest('tr');
      toggleOficial(tr.dataset.id);
    });
  });

  tbody.querySelectorAll('.btn-del').forEach(btn => {
    btn.addEventListener('click', () => {
      const tr = btn.closest('tr');
      excluirExercicio(tr.dataset.id);
    });
  });

  tbody.querySelectorAll('.btn-periodos').forEach(btn => {
    btn.addEventListener('click', () => {
      const tr = btn.closest('tr');
      abrirPeriodos(parseInt(tr.dataset.id, 10));
    });
  });
}

function editar(e) {
  document.getElementById('cdexercicio').value = e.cdexercicio;
  document.getElementById('anoref').value = e.anoref;
  document.getElementById('descricao').value = e.descricao;
  document.getElementById('floficial').checked = e.floficial == 1;
  modalExercicio.show();
}

function abrirPeriodos(id) {
  const e = cacheExercicios.get(parseInt(id, 10));
  if (!e) return;

  const titulo = document.getElementById('periodosTitulo');
  titulo.textContent = `Períodos do exercício ${e.anoref} - ${e.descricao}`;

  const status = {};
  for (let m = 1; m <= 12; m++) status[m] = true;
  if (Array.isArray(e.meses)) {
    e.meses.forEach(m => {
      status[parseInt(m.mesref, 10)] = !!m.flaberto;
    });
  }

  const nomes = ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'];
  const cont = document.getElementById('periodosContainer');
  let html = '';
  for (let m = 1; m <= 12; m++) {
    const aberto = !!status[m];
    const cls = aberto ? 'btn-success' : 'btn-outline-secondary';
    html += `
      <div class="col-6 col-md-3">
        <button type="button" class="btn btn-sm w-100 mes-btn ${cls}" data-mes="${m}" data-id="${e.cdexercicio}">
          ${nomes[m-1]}
        </button>
      </div>`;
  }
  cont.innerHTML = html;

  cont.querySelectorAll('.mes-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const mes = parseInt(btn.dataset.mes, 10);
      toggleMes(e.cdexercicio, mes, btn);
    });
  });

  modalPeriodos.show();
}

async function toggleAtivo(id) {
  if (!confirm('Deseja alterar o status deste exercício?')) return;
  const resp = await fetch('?m=exercicios_actions&ajax=toggle', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: `cdexercicio=${id}`
  }).then(r => r.json());
  if (!resp.ok) return alert(resp.msg || 'Erro');
  carregarLista();
}

async function toggleOficial(id) {
  const resp = await fetch('?m=exercicios_actions&ajax=oficial', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: `cdexercicio=${id}`
  }).then(r => r.json());
  if (!resp.ok) return alert(resp.msg || 'Erro');
  carregarLista();
}

async function excluirExercicio(id) {
  const tr = document.querySelector(`tr[data-id="${id}"]`);
  const ano = tr ? tr.dataset.anoref : '';
  const desc = tr ? tr.dataset.descricao : '';
  const msg = `Deseja excluir definitivamente o exercício ${ano} - ${desc}? Esta operação só é permitida se não houver lançamentos em realizado.`;
  if (!confirm(msg)) return;

  try {
    const resp = await fetch('?m=exercicios_actions&ajax=excluir', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: `cdexercicio=${encodeURIComponent(id)}`
    }).then(r => r.json());

    alert(resp.msg || (resp.ok ? 'Operação concluída' : 'Erro ao excluir'));
    if (resp.ok) {
      carregarLista();
    }
  } catch (err) {
    alert(err.message);
  }
}

async function toggleMes(cdexercicio, mes, btn) {
  try {
    const resp = await fetch('?m=exercicios_actions&ajax=toggle_mes', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: `cdexercicio=${cdexercicio}&mesref=${mes}`
    }).then(r => r.json());
    if (!resp.ok) {
      alert(resp.msg || 'Erro ao atualizar período');
      return;
    }

    const aberto = !!resp.flaberto;
    btn.classList.toggle('btn-success', aberto);
    btn.classList.toggle('btn-outline-secondary', !aberto);

    const e = cacheExercicios.get(parseInt(cdexercicio, 10));
    if (e) {
      if (!Array.isArray(e.meses)) e.meses = [];
      const idx = e.meses.findIndex(m => parseInt(m.mesref, 10) === mes);
      if (idx >= 0) {
        e.meses[idx].flaberto = aberto;
      } else {
        e.meses.push({ mesref: mes, flaberto: aberto });
      }
    }
  } catch (err) {
    alert(err.message);
  }
}

// Inicial
document.querySelector('.filtro[data-status="ativas"]').classList.add('active');
carregarLista();
</script>
