<?php
if (ob_get_level()) { ob_end_clean(); }
ob_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING & ~E_DEPRECATED);

require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/PdfHelper.php';
requireLogin();

$type   = $_GET['type']   ?? 'sale';
$format = $_GET['format'] ?? 'csv';
$status = $_GET['status'] ?? '';
$from   = $_GET['from']   ?? date('Y-m-01');
$to     = $_GET['to']     ?? date('Y-m-d');

ob_end_clean();

$invoiceType = $type === 'manual' ? 'manual' : 'sale';

$where  = ["i.invoice_type = '$invoiceType'"];
$params = [];
if ($status) { $where[] = "i.payment_status = ?"; $params[] = $status; }
$where[] = "i.invoice_date >= ?"; $params[] = $from;
$where[] = "i.invoice_date <= ?"; $params[] = $to;
$whereSql = 'WHERE ' . implode(' AND ', $where);

$stmt = $pdo->prepare("SELECT i.invoice_no, c.customer_name, i.invoice_date,
    i.subtotal, i.cgst_amount, i.sgst_amount, i.grand_total, i.paid_amount,
    (i.grand_total - i.paid_amount) balance, i.payment_status, i.payment_date, i.payment_mode
    FROM invoices i JOIN sale_vendors c ON c.id=i.customer_id
    $whereSql ORDER BY i.invoice_date DESC, i.id DESC");
$stmt->execute($params);
$rows = $stmt->fetchAll();

$title   = $type === 'manual' ? 'Manual/Service Bills' : 'Sale Bills';
$headers = ['Invoice No','Customer','Date','Subtotal','CGST','SGST','Grand Total','Paid','Balance','Status','Payment Date','Mode'];

if ($format === 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . strtolower(str_replace('/','',$title)) . '_' . date('Ymd') . '.csv"');
    $fp = fopen('php://output','w');
    fputcsv($fp, $headers);
    foreach ($rows as $r) {
        fputcsv($fp, [
            $r['invoice_no'], $r['customer_name'], $r['invoice_date'],
            $r['subtotal'], $r['cgst_amount'], $r['sgst_amount'], $r['grand_total'],
            $r['paid_amount'], $r['balance'], $r['payment_status'],
            $r['payment_date'] ?? '', $r['payment_mode'] ?? ''
        ]);
    }
    fclose($fp); exit;
}

if ($format === 'excel') {
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="' . strtolower(str_replace('/','',$title)) . '_' . date('Ymd') . '.xls"');
    echo '<table border="1">';
    echo '<tr><th colspan="' . count($headers) . '"><b>' . htmlspecialchars($title) . ' — ' . htmlspecialchars($from) . ' to ' . htmlspecialchars($to) . '</b></th></tr>';
    echo '<tr>' . implode('',array_map(fn($h) => "<th><b>$h</b></th>", $headers)) . '</tr>';
    foreach ($rows as $r) {
        echo '<tr>';
        $cols = [$r['invoice_no'],$r['customer_name'],$r['invoice_date'],
                 $r['subtotal'],$r['cgst_amount'],$r['sgst_amount'],$r['grand_total'],
                 $r['paid_amount'],$r['balance'],$r['payment_status'],
                 $r['payment_date']??'',$r['payment_mode']??''];
        foreach ($cols as $c) echo '<td>' . htmlspecialchars($c ?? '') . '</td>';
        echo '</tr>';
    }
    echo '</table>'; exit;
}

if ($format === 'pdf') {
    $totalBilled = array_sum(array_column($rows,'grand_total'));
    $totalPaid   = array_sum(array_column($rows,'paid_amount'));
    $totalDue    = $totalBilled - $totalPaid;
    ob_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?= htmlspecialchars($title) ?></title>
<style>
body{font-family:Arial,Helvetica,sans-serif;font-size:11px;margin:20px;}
h2{color:#1D4E4A;margin-bottom:2px;}
.meta{color:#75716A;font-size:10px;margin-bottom:8px;}
.summary{display:flex;gap:32px;margin-bottom:12px;background:#F6F4EF;padding:8px 12px;border-radius:6px;}
.sum-item .lbl{font-size:9px;text-transform:uppercase;color:#75716A;}
.sum-item .val{font-size:15px;font-weight:bold;color:#1D4E4A;}
table{width:100%;border-collapse:collapse;font-size:10px;}
th{background:#1D4E4A;color:#fff;padding:5px 6px;text-align:left;white-space:nowrap;}
td{padding:4px 6px;border-bottom:1px solid #E0DBCE;}
tr:nth-child(even) td{background:#FBFAF6;}
.num{text-align:right;}
.paid{color:#3B6D11;font-weight:bold;}
.pending{color:#A32D2D;font-weight:bold;}
.partial{color:#854F0B;font-weight:bold;}
</style>
</head>
<body>
<h2><?= htmlspecialchars($title) ?></h2>
<div class="meta">Period: <?= htmlspecialchars($from) ?> to <?= htmlspecialchars($to) ?><?= $status ? ' | Status: ' . htmlspecialchars($status) : '' ?> | Generated: <?= date('d-M-Y H:i A') ?></div>
<div class="summary">
    <div class="sum-item"><div class="lbl">Total Billed</div><div class="val">Rs. <?= number_format($totalBilled,2) ?></div></div>
    <div class="sum-item"><div class="lbl">Total Received</div><div class="val" style="color:#3B6D11;">Rs. <?= number_format($totalPaid,2) ?></div></div>
    <div class="sum-item"><div class="lbl">Outstanding</div><div class="val" style="color:#A32D2D;">Rs. <?= number_format($totalDue,2) ?></div></div>
    <div class="sum-item"><div class="lbl">Records</div><div class="val"><?= count($rows) ?></div></div>
</div>
<table>
<thead><tr>
<?php foreach ($headers as $h): ?><th><?= $h ?></th><?php endforeach; ?>
</tr></thead>
<tbody>
<?php foreach ($rows as $r): ?>
<tr>
    <td><?= htmlspecialchars($r['invoice_no']) ?></td>
    <td><?= htmlspecialchars($r['customer_name']) ?></td>
    <td><?= date('d-M-Y', strtotime($r['invoice_date'])) ?></td>
    <td class="num">Rs. <?= number_format($r['subtotal'],2) ?></td>
    <td class="num">Rs. <?= number_format($r['cgst_amount'],2) ?></td>
    <td class="num">Rs. <?= number_format($r['sgst_amount'],2) ?></td>
    <td class="num"><b>Rs. <?= number_format($r['grand_total'],2) ?></b></td>
    <td class="num paid">Rs. <?= number_format($r['paid_amount'],2) ?></td>
    <td class="num <?= $r['balance']>0?'pending':'' ?>">Rs. <?= number_format($r['balance'],2) ?></td>
    <td class="<?= $r['payment_status'] ?>"><?= strtoupper($r['payment_status']) ?></td>
    <td><?= $r['payment_date'] ? date('d-M-Y', strtotime($r['payment_date'])) : '-' ?></td>
    <td><?= htmlspecialchars($r['payment_mode'] ?? '-') ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body></html>
<?php
    $html = ob_get_clean();
    PdfHelper::output($html, strtolower(str_replace('/','',$title)) . '_' . date('Ymd') . '.pdf');
}
