<?php
// finance_archive.php — Voided invoices (status = 5)

$T = $_GET['t'] ?? 'includes/finance';
$P = $_GET['p'] ?? 'finance_archive.php';
$SELF = 'index.php?t=' . rawurlencode($T) . '&p=' . rawurlencode($P);

$selYear  = isset($_GET['y']) ? (int)$_GET['y'] : 0;
$selMonth = isset($_GET['m']) ? (int)$_GET['m'] : 0;
$fromStr  = trim($_GET['from'] ?? '');
$toStr    = trim($_GET['to'] ?? '');

$parseDMY = function(string $dmy): ?int {
    $dmy = trim($dmy);
    if ($dmy === '') return null;

    // normalise separators
    $dmy = str_replace('/', '-', $dmy);

    // allow 1-2 digit day/month, 4-digit year
    if (!preg_match('/^\s*(\d{1,2})-(\d{1,2})-(\d{4})\s*$/', $dmy, $m)) return null;
    [$all, $d, $mth, $y] = $m;
    return @mktime(0, 0, 0, (int)$mth, (int)$d, (int)$y) ?: null;
};

// Compute time window (inclusive start, exclusive end)
$timeMin = null;
$timeMax = null;

if ($fromStr !== '' || $toStr !== '') {
    $fromTs = $fromStr !== '' ? $parseDMY($fromStr) : null;
    $toTs   = $toStr   !== '' ? $parseDMY($toStr)   : null;

    if ($fromTs && $toTs) {
        $timeMin = $fromTs;
        $timeMax = strtotime('+1 day', $toTs); // exclusive
    } elseif ($fromTs && !$toTs) {
        // If only "From" is given, default "To" to today (end of day)
        $timeMin = $fromTs;
        $today0  = mktime(0, 0, 0, (int)date('n'), (int)date('j'), (int)date('Y'));
        $timeMax = strtotime('+1 day', $today0);
    } elseif (!$fromTs && $toTs) {
        // If only "To" is given, all time up to end of that day
        $timeMax = strtotime('+1 day', $toTs);
    }
} elseif ($selYear > 0 && $selMonth > 0) {
    $timeMin = mktime(0, 0, 0, $selMonth, 1, $selYear);
    $timeMax = strtotime('+1 month', $timeMin);
} elseif ($selYear > 0) {
    $timeMin = mktime(0, 0, 0, 1, 1, $selYear);
    $timeMax = strtotime('+1 year', $timeMin);
} else {
    $timeMin = mktime(0, 0, 0, (int)date('n'), 1, (int)date('Y'));
    $timeMax = strtotime('+1 month', $timeMin);
}


$idxSql = "SELECT `date` FROM `invoices` WHERE `status`=5";
$idxStmt = $GLOBALS['con']->prepare($idxSql) or die(mysqli_error($GLOBALS['con']));
$idxStmt->execute();
$idxRs = $idxStmt->get_result();
$idxStmt->close();

$yrMo = []; // [year => ['total'=>int, 'months'=>[m=>count]]]
while ($r = mysqli_fetch_assoc($idxRs)) {
    $ts = (int)($r['date'] ?? 0);
    if ($ts <= 0) continue;
    $y = (int)date('Y', $ts);
    $m = (int)date('n', $ts);
    if (!isset($yrMo[$y])) $yrMo[$y] = ['total'=>0,'months'=>[]];
    $yrMo[$y]['total']++;
    if (!isset($yrMo[$y]['months'][$m])) $yrMo[$y]['months'][$m] = 0;
    $yrMo[$y]['months'][$m]++;
}
// Sort years desc, months asc
krsort($yrMo);
foreach ($yrMo as &$info) {
    ksort($info['months']);
}
unset($info);

$sql = "SELECT * FROM `invoices` WHERE `status`=5";
$params = [];
$types  = '';

if ($timeMin !== null) {
    $sql .= " AND `date` >= ?";
    $params[] = $timeMin;
    $types    .= 'i';
}
if ($timeMax !== null) {
    $sql .= " AND `date` < ?";
    $params[] = $timeMax;
    $types    .= 'i';
}
$sql .= " ORDER BY ABS(invno) ASC";

$stmt = $GLOBALS['con']->prepare($sql) or die(mysqli_error($GLOBALS['con']));
if ($types !== '') {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$rs = $stmt->get_result();
$stmt->close();

$data = [];
while ($row = mysqli_fetch_array($rs)) $data[] = $row;
$hasRows = !empty($data);

function monthName(int $m): string {
    static $names = [1=>'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    return $names[$m] ?? (string)$m;
}
?>

<style>
@media (min-width: 992px) {
    .sidebar-hidden #invoiceSidebar {
        display: none !important;
    }

    .sidebar-hidden #invoiceMain {
        flex: 0 0 100% !important;
        max-width: 100% !important;
    }
}

@media (min-width: 992px) {
    #invoiceSidebar {
        height: 75vh;
        border: 1px solid #ccc;
        border-radius: 5px;
        border-right: 5px solid var(--primary-color);
        box-shadow: 4px 0 8px rgba(0, 0, 0, 0.1);
        background-color: var(--mdb-light-bg-subtle);
        position: sticky;
        top: 0;
    }
}
</style>

<script>
document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item"><a href="index.php?t=includes/finance&p=finance_invoices.php">Finance - Invoices</a> ' +
    '<i class="fad fa-angle-double-right mx-2 mt-1"></i></li>' +
    '<li class="breadcrumb-item active">Voided</li>';
</script>

<div id="invoiceData" class="container-fluid px-0">
    <?php
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `invoices` WHERE `status`='1' or `status`='2'") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
        $i = $stmt->get_result();
        $stmt->close();
        $unpaidCount = mysqli_num_rows($i);

        $stmt = $GLOBALS['con']->prepare("SELECT * FROM `invoices_temp`") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
        $i = $stmt->get_result();
        $stmt->close();
        $renewalCount = mysqli_num_rows($i);
?>
    <div class="row">
        <div class="col-12 col-md-9 float-start">
            <div class="btn-group me-2 mb-4 active" role="group" aria-label="New Invoice">
                <a href="index.php?t=includes/finance&p=finance_invoices-new.php" class="btn btn-success ">New Invoice</a>
            </div>
            <div class="btn-group me-2 mb-4" role="group" aria-label="Blank Invoice">
                <a href="index.php?t=includes/finance&p=finance_invoice_blank.php" class="btn btn-dark">Blank Invoice</a>
            </div>
            <div class="btn-group me-2 mb-4" role="group" aria-label="Unpaid Invoices">
                <a href="index.php?t=includes/finance&p=finance_unpaid.php" class="btn btn-outline-secondary">Unpaid Invoices <span class="badge rounded-pill bg-dark ms-2"><?= $unpaidCount ?></span></a>
            </div>
            <div class="btn-group me-2 mb-4" role="group" aria-label="Paid Invoices">
                <a href="index.php?t=includes/finance&p=finance_paid.php" class="btn btn-outline-secondary">Paid Invoices</a>
            </div>
            <div class="btn-group me-2 mb-4" role="group" aria-label="Renewal Invoice">
                <a href="index.php?t=includes/finance&p=finance_renewal_invoice.php" class="btn btn-outline-secondary">Renewal Invoice <span class="badge rounded-pill bg-dark ms-2"><?= $renewalCount ?></span></a>
            </div>
            <div class="btn-group me-2 mb-4" role="group" aria-label="Voided Invoices">
                <a href="index.php?t=includes/finance&p=finance_archive.php" class="btn btn-outline-secondary active"><span class="text-danger">Voided Invoices</span></a>
            </div>
        </div>
        <div class="col-12 col-md-3">
            <a href="index.php?t=includes/finance&p=invoicePaid_reports.php" class="btn btn-secondary float-end" data-mdb-toggle="tooltip" title="View Reports"> <i class="fad fa-file-invoice me-1"></i> Create Report
            </a>
        </div>
    </div>


    <div class="mb-2 mb-md-0">
        <div class="note note-light mb-3">
            <strong>Voided invoices:</strong> All invoices with status <code>5</code>.
            <small class="mt-1">Open a copy for viewing. Use the sidebar to filter by year, month, or date range.</small>
        </div>
    </div>


    <div class="row g-3">
        <!-- Sidebar -->
        <aside id="invoiceSidebar" class="col-12 col-lg-3 px-3">
            <div class="d-flex d-lg-none justify-content-between align-items-center mb-2">
                <h6 class="mb-0">Filter</h6>
                <button class="btn btn-outline-secondary btn-sm" type="button" data-mdb-collapse-init
                        data-mdb-target="#invIndexCollapse" aria-expanded="false" aria-controls="invIndexCollapse">
                    Toggle
                </button>
            </div>

            <div class="collapse d-lg-block" id="invIndexCollapse">
                <label class="mt-2 mb-2">Data Explorer</label>
                <div class="mb-3">
                    <a class="btn btn-secondary btn-sm w-100"
                       href="<?= $SELF ?>&y=<?= date('Y') ?>&m=<?= date('n') ?>">
                        This Month (<?= date('M Y') ?>)
                    </a>
                </div>

                <?php $openYear = $selYear ?: (int)date('Y'); ?>

                <!-- Year / Month index (collapsible, one open at a time) -->
                <div class="list-group">
                    <?php if (!empty($yrMo)): foreach ($yrMo as $y => $info): 
                        $isOpen = ($y === $openYear);
                        $collapseId = "yearMonths-$y";
                ?>
                    <div class="mb-2 border rounded">
                        <div class="d-flex align-items-center justify-content-between">
                            <!-- Toggle button: expands months without navigation -->
                            <button type="button"
                                    class="list-group-item list-group-item-action py-2 flex-grow-1 text-start border-0 bg-transparent"
                                    data-year-toggle="<?= $y ?>"
                                    aria-controls="<?= $collapseId ?>"
                                    aria-expanded="<?= $isOpen ? 'true':'false' ?>">
                                <span class="me-2">
                                    <i class="fad fa-chevron-<?= $isOpen ? 'down' : 'right' ?>"></i>
                                </span>
                                <?= $y ?>
                                <span class="badge bg-dark ms-2"><?= (int)$info['total'] ?></span>
                            </button>

                            <!-- Explicit "View Year" link (does filter) -->
                            <a class="btn btn-outline-secondary btn-sm me-2"
                               href="<?= $SELF ?>&y=<?= $y ?>"
                               title="View <?= $y ?>">View</a>
                        </div>

                        <div id="<?= $collapseId ?>" class="ps-2 pt-1 collapse <?= $isOpen ? 'show' : '' ?>">
                            <?php foreach ($info['months'] as $m => $cnt): ?>
                            <a class="list-group-item list-group-item-action py-1 <?= ($y === $selYear && $m === $selMonth) ? 'active' : '' ?>"
                               href="<?= $SELF ?>&y=<?= $y ?>&m=<?= $m ?>">
                                <?= monthName($m) ?>
                                <span class="badge bg-light text-dark ms-2"><?= (int)$cnt ?></span>
                            </a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endforeach; else: ?>
                    <div class="text-muted small">No invoices found.</div>
                    <?php endif; ?>
                </div>

                <!-- Date Range -->
                <hr class="my-3">
                <form id="rangeForm" class="vstack gap-2" onsubmit="return applyRange(event)">
                    <div class="row">
                        <div class="col-12 col-md-6 date-picker" data-date-type="open" data-format="dd-mm-yyyy" data-mdb-toggle-button="false">
                            <label class="form-label small mb-1">From</label>
                            <input class="form-control form-control-sm" data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker" id="range_from" name="from" placeholder="dd-mm-yyyy" autocomplete="off"
                                   value="<?= htmlspecialchars($fromStr) ?>">
                        </div>
                        <?php $todayDMY = date('d-m-Y'); ?>
                        <div class="col-12 col-md-6 date-picker" data-date-type="open" data-format="dd-mm-yyyy" data-mdb-toggle-button="false">
                            <label class="form-label small mb-1">To</label>
                            <input class="form-control form-control-sm" data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker" id="range_to" name="to" placeholder="dd-mm-yyyy" autocomplete="off"
                                   value="<?= htmlspecialchars($toStr !== '' ? $toStr : $todayDMY) ?>">
                        </div>
                    </div>
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-secondary btn-sm w-100">Search</button>
                        <a href="<?= $SELF ?>" class="btn btn-outline-secondary btn-sm w-100">Reset</a>
                    </div>
                </form>
            </div>
        </aside>

        <!-- Main -->
        <section id="invoiceMain" class="col-12 col-lg-9">
            <div class="col-12 col-lg-3 mx-n2 mb-3">
                <button id="toggleSidebar"
                        type="button"
                        class="btn btn-outline-secondary btn-sm ms-2"
                        data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                        title="Toggle sidebar">
                    <i class="fad fa-columns me-1"></i> <span class="filters-label">Open filters</span>
                </button>
            </div>
            <?php if (!$hasRows): ?>
            <h3 class="text-center text-warning">There are no items to display yet for this month</h3>
            <p class="text-center text-muted">Use the filter panel to view historic data</p>
            <?php else: ?>
            <table id="expenseTable" class="table table-striped table-hover align-middle w-100 table-sm">
                <thead class="table-dark">
                    <tr>
                        <th>Invoice #</th>
                        <th>Client</th>
                        <th>Broker/Agent</th>
                        <th>Contract #</th>
                        <th>Amount</th>
                        <th>Date of Invoice</th>
                        <th class="text-end noExport">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
          $mTotal = 0;
          foreach ($data as $row):
              $invNo = (int)$row['invNo'];
              $invNoFormatted = sprintf("%06d", $invNo);
              $address = @unserialize($row['address']); if (!is_array($address)) $address = [];
              $totals = explode('|', $row['totals']);
              $sub = (float)str_replace(',', '', $totals[0] ?? '0');
              $vat = (float)str_replace(',', '', $totals[1] ?? '0');
              $grand = $sub + $vat;
              $mTotal += $grand;

              $invoiceDate = !empty($row['date']) ? date('d-m-Y', (int)$row['date']) : '';

              // Display names
              $target = strtolower((string)($row['target'] ?? 'client'));
              $clientDisplay = '';
              $brokerAgentDisplay = '';

              if ($target === 'blank') {
                  // Blank invoice: use saved company/billing name from address
                  $clientDisplay = htmlspecialchars($address['billing_name'] ?? ($address['client_name'] ?? ''));
              } else {
                  // Normal client path
                  $cName = '';
                  $cStmt = $GLOBALS['con']->prepare("SELECT clientname FROM clientdetails WHERE clientnumber=? LIMIT 1");
                  $cStmt->bind_param('i', $row['client']);
                  $cStmt->execute();
                  $cRes = $cStmt->get_result();
                  $cStmt->close();
                  if ($cRes && $cRes->num_rows) {
                      $cRow = mysqli_fetch_assoc($cRes);
                      $cName = $cRow['clientname'] ?? '';
                  }
                  $clientDisplay = htmlspecialchars($cName);
              }

              if ($target === 'agent') {
                  $aName = $address['agent_name'] ?? '';
                  // Try live name if ID present
                  if (!empty($row['agent'])) {
                      $aStmt = $GLOBALS['con']->prepare("SELECT agent_name FROM agents WHERE agent_number=? LIMIT 1");
                      $aStmt->bind_param('i', $row['agent']);
                      $aStmt->execute();
                      $aRes = $aStmt->get_result();
                      $aStmt->close();
                      if ($aRes && $aRes->num_rows) {
                          $aRow = mysqli_fetch_assoc($aRes);
                          $aName = $aRow['agent_name'] ?? $aName;
                      }
                  }
                  $brokerAgentDisplay = htmlspecialchars($aName);
              } elseif ($target === 'broker') {
                  $bName = $address['broker_name'] ?? '';
                  if (!empty($row['broker'])) {
                      $bStmt = $GLOBALS['con']->prepare("SELECT broker_name FROM brokers WHERE broker_number=? LIMIT 1");
                      $bStmt->bind_param('i', $row['broker']);
                      $bStmt->execute();
                      $bRes = $bStmt->get_result();
                      $bStmt->close();
                      if ($bRes && $bRes->num_rows) {
                          $bRow = mysqli_fetch_assoc($bRes);
                          $bName = $bRow['broker_name'] ?? $bName;
                      }
                  }
                  $brokerAgentDisplay = htmlspecialchars($bName);
              } else {
                  $brokerAgentDisplay = htmlspecialchars($address['agent_name'] ?? '');
              }

              $contractNum = htmlspecialchars($address['contract_number'] ?? '');
              $grandFmt = number_format($grand, 2);
          ?>
                    <tr id="R<?= $invNoFormatted ?>">
                        <td><?= $invNoFormatted ?></td>
                        <td><?= $clientDisplay ?></td>
                        <td><?= $brokerAgentDisplay ?></td>
                        <td><?= $contractNum ?></td>
                        <td>£<?= $grandFmt ?></td>
                        <td><?= $invoiceDate ?></td>
                        <td class="text-end">
                            <a href="index.php?t=includes/finance&p=finance_preview.php&invNo=<?= $invNo ?>&type=archive"
                               class="btn btn-secondary btn-sm me-2"
                               data-mdb-toggle="tooltip" title="View Invoice">
                                <i class="fad fa-eye"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <div class="d-flex justify-content-end px-3 mt-3">
                <span class="fw-bold">Total Voided: £<?= number_format($mTotal, 2) ?></span>
            </div>
            <?php endif; ?>
        </section>
    </div>
</div>

<div id="exportDiv" style="display:none">
    <div id="exportTitle">Voided Invoices - <small>Generated <?= date('d-m-Y') ?></small></div>
    <table id="exportTable" class="table table-striped table-sm responsive" width="100%">
        <thead>
            <tr>
                <th>Invoice Number</th>
                <th>Client</th>
                <th>Broker/Agent</th>
                <th>Contract Number</th>
                <th>Amount</th>
                <th>Date of Invoice</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($data as $row):
        $invNo = (int)$row['invNo'];
        $invNoFormatted = sprintf("%06d", $invNo);
        $address = @unserialize($row['address']); if (!is_array($address)) $address = [];
        $totals = explode('|', $row['totals']);
        $sub = (float)str_replace(',', '', $totals[0] ?? '0');
        $vat = (float)str_replace(',', '', $totals[1] ?? '0');
        $grand = $sub + $vat;

        $target = strtolower((string)($row['target'] ?? 'client'));
        if ($target === 'blank') {
          $clientDisplay = htmlspecialchars($address['billing_name'] ?? ($address['client_name'] ?? ''));
        } else {
          $cName = '';
          $cStmt = $GLOBALS['con']->prepare("SELECT clientname FROM clientdetails WHERE clientnumber=? LIMIT 1");
          $cStmt->bind_param('i', $row['client']);
          $cStmt->execute();
          $cRes = $cStmt->get_result();
          $cStmt->close();
          if ($cRes && $cRes->num_rows) {
              $cRow = mysqli_fetch_assoc($cRes);
              $cName = $cRow['clientname'] ?? '';
          }
          $clientDisplay = htmlspecialchars($cName);
        }

        if ($target === 'agent') {
          $brokerAgent = htmlspecialchars($address['agent_name'] ?? '');
        } elseif ($target === 'broker') {
          $brokerAgent = htmlspecialchars($address['broker_name'] ?? '');
        } else {
          $brokerAgent = htmlspecialchars($address['agent_name'] ?? '');
        }
      ?>
            <tr id="R<?= $invNoFormatted ?>">
                <td><?= $invNoFormatted ?></td>
                <td><?= $clientDisplay ?></td>
                <td><?= $brokerAgent ?></td>
                <td><?= htmlspecialchars($address['contract_number'] ?? '') ?></td>
                <td>£<?= number_format($grand, 2) ?></td>
                <td><?= !empty($row['date']) ? date('d-m-Y', (int)$row['date']) : '' ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php
// DataTable config (consistent)
$table = "expenseTable";
$dateTarget = "5";
$length = "25";
$sortTarget = "1";
$sortCell = "";
$logo = "yes";
$scroller = "";
$printTarget = 'exportDiv';
$printHeader = 'Voided Invoices';
$popup = "false";
require(ROOT_URL . '/includes/tables/finance_table.php');
?>

<script>
// Tooltips
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('[data-mdb-toggle="tooltip"]').forEach(el => new mdb.Tooltip(el));
});

// Date range submit → redirect preserving t & p
function applyRange(ev) {
    ev.preventDefault();
    const from = (document.getElementById('range_from')?.value || '').trim();
    const to = (document.getElementById('range_to')?.value || '').trim();
    const base = "<?= $SELF ?>";
    const qs = new URLSearchParams();
    if (from) qs.set('from', from);
    if (to) qs.set('to', to);
    const url = qs.toString() ? (base + '&' + qs.toString()) : base;
    window.location.href = url;
    return false;
}

document.addEventListener('DOMContentLoaded', () => {
    // Collapse logic: only one year open at a time
    document.body.addEventListener('click', (ev) => {
        const btn = ev.target.closest('[data-year-toggle]');
        if (!btn) return;

        const year = btn.getAttribute('data-year-toggle');
        const targetId = btn.getAttribute('aria-controls');
        const target = document.getElementById(targetId);
        if (!target) return;

        // Close all other year groups
        document.querySelectorAll('[id^="yearMonths-"]').forEach(el => {
            if (el.id !== targetId) {
                el.classList.remove('show');
                const otherBtn = document.querySelector(`[data-year-toggle][aria-controls="${el.id}"]`);
                if (otherBtn) {
                    otherBtn.setAttribute('aria-expanded', 'false');
                    const icon = otherBtn.querySelector('.fa-chevron-down, .fa-chevron-right');
                    if (icon) {
                        icon.classList.remove('fa-chevron-down');
                        icon.classList.add('fa-chevron-right');
                    }
                }
            }
        });

        // Toggle clicked group
        const willOpen = !target.classList.contains('show');
        target.classList.toggle('show', willOpen);
        btn.setAttribute('aria-expanded', willOpen ? 'true' : 'false');

        // Update chevron
        const icon = btn.querySelector('.fa-chevron-down, .fa-chevron-right');
        if (icon) {
            icon.classList.toggle('fa-chevron-down', willOpen);
            icon.classList.toggle('fa-chevron-right', !willOpen);
        }
    });
});

document.addEventListener('DOMContentLoaded', () => {
    // Ensure closed on load
    document.body.classList.add('sidebar-hidden');

    const btn = document.getElementById('toggleSidebar');
    const label = btn?.querySelector('.filters-label');

    function setFiltersLabel() {
        const open = !document.body.classList.contains('sidebar-hidden');
        if (label) label.textContent = open ? 'Close filters' : 'Open filters';
    }

    setFiltersLabel();

    if (btn) {
        btn.addEventListener('click', () => {
            document.body.classList.toggle('sidebar-hidden');
            setFiltersLabel();
        });
    }
});
</script>