<?php
require_once '../includes/auth.php';
requirePermission('reports', 'export');
require_once '../db.php';

require_once '../vendor/autoload.php';
use Dompdf\Dompdf;

$client_id = (int)($_GET['client_id'] ?? 0);
$from_date = $_GET['from_date'] ?? date('Y-m-01');
$to_date   = $_GET['to_date'] ?? date('Y-m-d');

if ($client_id <= 0) {
    die("Invalid Client");
}

$client = $conn->query("SELECT * FROM clients WHERE id=$client_id")->fetch_assoc();
if (!$client) die("Customer not found");

$opening = (float)($client['opening_balance'] ?? 0);

$ledgerRows = [];

// FINAL invoices only
$invQuery = $conn->query("
    SELECT invoice_no, invoice_date, net_total, received_amount, payment_mode
    FROM sales_invoices
    WHERE client_id = $client_id
      AND status = 'final'
      AND company_id = $cid
      AND invoice_date BETWEEN '$from_date' AND '$to_date'
    ORDER BY invoice_date ASC, id ASC
");

while ($inv = $invQuery->fetch_assoc()) {

    $ledgerRows[] = [
        'date' => $inv['invoice_date'],
        'type' => 'Sales Invoice',
        'ref'  => $inv['invoice_no'],
        'debit' => (float)$inv['net_total'],
        'credit' => 0,
        'note' => ''
    ];

    if ((float)$inv['received_amount'] > 0) {
        $ledgerRows[] = [
            'date' => $inv['invoice_date'],
            'type' => 'Payment Received',
            'ref'  => $inv['invoice_no'],
            'debit' => 0,
            'credit' => (float)$inv['received_amount'],
            'note' => $inv['payment_mode'] ?? ''
        ];
    }
}

// FINAL returns only
$retQuery = $conn->query("
    SELECT return_no, return_date, total_amount
    FROM sales_returns
    WHERE client_id = $client_id
      AND status = 'final'
      AND company_id = $cid
      AND return_date BETWEEN '$from_date' AND '$to_date'
    ORDER BY return_date ASC, id ASC
");

while ($ret = $retQuery->fetch_assoc()) {
    $ledgerRows[] = [
        'date' => $ret['return_date'],
        'type' => 'Sales Return',
        'ref'  => $ret['return_no'],
        'debit' => 0,
        'credit' => (float)$ret['total_amount'],
        'note' => ''
    ];
}

// Sort by date
usort($ledgerRows, function($a, $b){
    return strtotime($a['date']) <=> strtotime($b['date']);
});

$balance = $opening;

// Build HTML
$html = '
<style>
    body { font-family: DejaVu Sans, sans-serif; font-size: 12px; }
    h2 { text-align:center; margin-bottom: 5px; }
    .info { margin-bottom: 10px; padding: 8px; border: 1px solid #000; }
    table { width:100%; border-collapse: collapse; }
    th, td { border: 1px solid #000; padding: 6px; font-size: 11px; }
    th { background: #f2f2f2; }
    .r { text-align:right; }
    .opening { background:#fffbe6; font-weight:bold; }
    .closing { background:#eef7ff; font-weight:bold; }
</style>

<h2>Customer Ledger Report</h2>

<div class="info">
    <b>Customer:</b> '.htmlspecialchars($client['name']).'<br>
    <b>Phone:</b> '.htmlspecialchars($client['phone'] ?? '-').' &nbsp;&nbsp;
    <b>GSTIN:</b> '.htmlspecialchars($client['gstin'] ?? '-').'<br>
    <b>From:</b> '.$from_date.' &nbsp;&nbsp;
    <b>To:</b> '.$to_date.'
</div>

<table>
    <tr>
        <th>Date</th>
        <th>Particular</th>
        <th>Ref No</th>
        <th class="r">Debit</th>
        <th class="r">Credit</th>
        <th class="r">Balance</th>
        <th>Note</th>
    </tr>
';

// Opening row
$html .= '
<tr class="opening">
    <td>'.$from_date.'</td>
    <td>Opening Balance</td>
    <td>-</td>
    <td class="r">'.($balance > 0 ? number_format($balance,2) : "0.00").'</td>
    <td class="r">'.($balance < 0 ? number_format(abs($balance),2) : "0.00").'</td>
    <td class="r">'.number_format($balance,2).'</td>
    <td></td>
</tr>
';

foreach ($ledgerRows as $row) {
    $balance += $row['debit'];
    $balance -= $row['credit'];

    $html .= '
    <tr>
        <td>'.date('d-m-Y', strtotime($row['date'])).'</td>
        <td>'.htmlspecialchars($row['type']).'</td>
        <td>'.htmlspecialchars($row['ref']).'</td>
        <td class="r">'.number_format($row['debit'],2).'</td>
        <td class="r">'.number_format($row['credit'],2).'</td>
        <td class="r">'.number_format($balance,2).'</td>
        <td>'.htmlspecialchars($row['note']).'</td>
    </tr>
    ';
}

// Closing row
$html .= '
<tr class="closing">
    <td colspan="5" class="r">Closing Balance</td>
    <td class="r">'.number_format($balance,2).'</td>
    <td></td>
</tr>
';

$html .= '</table>';

// Dompdf
$dompdf = new Dompdf();
$dompdf->loadHtml($html);

$dompdf->setPaper('A4', 'portrait');
$dompdf->render();

// Direct download (no print preview)
$pdfName = "Customer_Ledger_".$client_id.".pdf";
$dompdf->stream($pdfName, ["Attachment" => true]);
exit;
