<?php
require_once __DIR__ . '/../inc/helpers.php';
require_once __DIR__ . '/../inc/docs.php';
require_login();
ensure_part2_tables();
if(!is_admin()){ http_response_code(403); exit('Solo admin'); }

$id=(int)($_GET['id']??0);
if($_SERVER['REQUEST_METHOD']!=='POST'){ http_response_code(405); exit('Método no permitido'); }
csrf_check();

// No permitir borrar si ya está pagada
$st=db()->prepare("SELECT * FROM documents WHERE id=? AND doc_type='invoice'");
$st->execute([$id]);
$inv=$st->fetch();
if(!$inv){ flash_set('danger','Factura no encontrada.'); redirect('facturas/list.php'); }
if(invoice_is_fully_paid($inv)){ flash_set('danger','No puedes borrar una factura pagada al 100%.'); redirect('facturas/list.php'); }

db()->prepare("DELETE FROM documents WHERE id=? AND doc_type='invoice'")->execute([$id]);
flash_set('success','Factura eliminada.');
redirect('facturas/list.php');
