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

$fromDate  = $_GET['from']   ?? date('Y-m-01');
$toDate    = $_GET['to']     ?? date('Y-m-d');
$typeFilter = $_GET['type']  ?? '';
$partyFilter = trim($_GET['party'] ?? '');
$modeFilter  = trim($_GET['mode']  ?? '');
$refFilter   = trim($_GET['ref']   ?? '');

$params = [$fromDate, $toDate];
$where  = ["DATE(p.payment_date) BETWEEN ? AND ?"];
if ($typeFilter)   { $where[] = "p.payment_type = ?";    $params[] = $typeFilter; }
if ($partyFilter)  { $where[] = "p.party_name LIKE ?";   $params[] = "%$partyFilter%"; }
if ($modeFilter)   { $where[] = "p.payment_mode = ?";    $params[] = $modeFilter; }
if ($refFilter)    { $where[] = "p.remarks LIKE ?";       $params[] = "%$refFilter%"; }
$whereSql = 'WHERE ' . implode(' AND ', $where);

// ── Summary ──────────────────────────────────────────────────
$stmt = $pdo->prepare("SELECT
    COALESCE(SUM(CASE WHEN p.payment_type='inflow' THEN p.amount ELSE 0 END),0) inflow,
    COALESCE(SUM(CASE WHEN p.payment_type='outflow' THEN p.amount ELSE 0 END),0) outflow,
    COUNT(*) transactions
    FROM payments p $whereSql");
$stmt->execute($params); $summary = $stmt->fetch();
$net = $summary['inflow'] - $summary['outflow'];

// ── All Transactions ──────────────────────────────────────────
$stmt = $pdo->prepare("SELECT p.*, u.name as marked_by_name
    FROM payments p LEFT JOIN users u ON u.id=p.created_by
    $whereSql ORDER BY p.payment_date DESC, p.id DESC");
$stmt->execute($params); $transactions = $stmt->fetchAll();

// ── Date-wise Summary ─────────────────────────────────────────
$stmt = $pdo->prepare("SELECT DATE(p.payment_date) pdate,
    COALESCE(SUM(CASE WHEN p.payment_type='inflow' THEN p.amount ELSE 0 END),0) inflow,
    COALESCE(SUM(CASE WHEN p.payment_type='outflow' THEN p.amount ELSE 0 END),0) outflow
    FROM payments p $whereSql GROUP BY pdate ORDER BY pdate DESC");
$stmt->execute($params); $dateWise = $stmt->fetchAll();

// ── Payment Modes ─────────────────────────────────────────────
$modes = $pdo->query("SELECT DISTINCT payment_mode FROM payments WHERE payment_mode IS NOT NULL ORDER BY payment_mode")->fetchAll(PDO::FETCH_COLUMN);

// ── Export ────────────────────────────────────────────────────
$export = $_GET['export'] ?? '';
if ($export) {
    $filename = 'cashflow_report_' . $fromDate . '_to_' . $toDate;
    if ($export === 'csv') {
        header('Content-Type: text/csv');
        header("Content-Disposition: attachment; filename=\"$filename.csv\"");
        $fp = fopen('php://output','w');
        fputcsv($fp, ['Date','Type','Party','Reference Type','Reference','Amount','Mode','Remarks','Marked By']);
        foreach ($transactions as $t) {
            fputcsv($fp, [
                date('d-M-Y H:i', strtotime($t['payment_date'])),
                strtoupper($t['payment_type']),
                $t['party_name'],
                $t['reference_type'],
                $t['reference_id'],
                $t['amount'],
                $t['payment_mode'],
                $t['remarks'],
                $t['marked_by_name'] ?? '-'
            ]);
        }
        fclose($fp); exit;
    }
    if ($export === 'excel') {
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment; filename=\"$filename.xls\"");
        echo '<table border="1"><tr><th colspan="9"><b>Cash Flow Report: '.$fromDate.' to '.$toDate.'</b></th></tr>';
        echo '<tr><th>Date</th><th>Type</th><th>Party</th><th>Ref Type</th><th>Ref</th><th>Amount</th><th>Mode</th><th>Remarks</th><th>Marked By</th></tr>';
        foreach ($transactions as $t) {
            echo '<tr><td>'.date('d-M-Y H:i',strtotime($t['payment_date'])).'</td><td>'.strtoupper($t['payment_type']).'</td><td>'.htmlspecialchars($t['party_name']).'</td><td>'.$t['reference_type'].'</td><td>'.$t['reference_id'].'</td><td>'.$t['amount'].'</td><td>'.htmlspecialchars($t['payment_mode']).'</td><td>'.htmlspecialchars($t['remarks']).'</td><td>'.htmlspecialchars($t['marked_by_name']??'-').'</td></tr>';
        }
        echo '</table>'; exit;
    }
    if ($export === 'pdf') {
        require_once __DIR__ . '/../../includes/PdfHelper.php';
        $html = '<!DOCTYPE html><html><head><meta charset="UTF-8"><style>body{font-family:Arial,sans-serif;font-size:10px;padding:16px;}h2,h3{color:#1D4E4A;}table{width:100%;border-collapse:collapse;margin-bottom:16px;}th{background:#1D4E4A;color:#fff;padding:5px;text-align:left;font-size:10px;}td{padding:4px 5px;border-bottom:1px solid #ddd;font-size:10px;}.num{text-align:right;}tr:nth-child(even) td{background:#f9f7f2;}.s{display:table-cell;padding:8px;background:#f0f7f0;border:1px solid #ccc;text-align:center;}.summary{display:table;width:100%;margin-bottom:12px;}</style></head><body>';
        $html .= '<h2>Cash Flow Report</h2><p>Period: '.date('d-M-Y',strtotime($fromDate)).' to '.date('d-M-Y',strtotime($toDate)).'</p>';
        $html .= '<div class="summary"><div class="s"><div style="font-size:9px;color:#666;">INFLOW</div><strong style="color:#080">&#8377;'.number_format($summary['inflow'],2).'</strong></div><div class="s"><div style="font-size:9px;color:#666;">OUTFLOW</div><strong style="color:#c00">&#8377;'.number_format($summary['outflow'],2).'</strong></div><div class="s"><div style="font-size:9px;color:#666;">NET</div><strong style="color:'.($net>=0?'#080':'#c00').'">&#8377;'.number_format(abs($net),2).($net<0?' (Deficit)':'').'</strong></div></div>';
        $html .= '<h3>All Transactions</h3><table><tr><th>Date</th><th>Type</th><th>Party</th><th>Ref</th><th class="num">Amount</th><th>Mode</th><th>Remarks</th><th>Marked By</th></tr>';
        foreach ($transactions as $t) {
            $clr = $t['payment_type']==='inflow'?'#080':'#c00';
            $html .= '<tr><td>'.date('d-M-Y',strtotime($t['payment_date'])).'</td><td style="color:'.$clr.';font-weight:bold;">'.strtoupper($t['payment_type']).'</td><td>'.htmlspecialchars($t['party_name']).'</td><td>'.htmlspecialchars($t['reference_type'].' #'.$t['reference_id']).'</td><td class="num" style="color:'.$clr.'">&#8377;'.number_format($t['amount'],2).'</td><td>'.htmlspecialchars($t['payment_mode']).'</td><td>'.htmlspecialchars(substr($t['remarks'],0,40)).'</td><td>'.htmlspecialchars($t['marked_by_name']??'-').'</td></tr>';
        }
        $html .= '</table></body></html>';
        PdfHelper::output($html, $filename.'.pdf', true); exit;
    }
}

$pageTitle = 'Cash Flow Report';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div><div class="eyebrow">Reports</div><h2 class="mb-0">Cash Flow Report</h2></div>
    <div class="flex gap-8" style="flex-wrap:wrap;align-items:center;">
        <form method="GET" class="flex gap-8" style="flex-wrap:wrap;">
            <input type="date" name="from" value="<?= sanitize($fromDate) ?>">
            <input type="date" name="to"   value="<?= sanitize($toDate) ?>">
            <select name="type" style="width:130px;">
                <option value="">All Types</option>
                <option value="inflow"  <?= $typeFilter==='inflow'?'selected':'' ?>>Inflow</option>
                <option value="outflow" <?= $typeFilter==='outflow'?'selected':'' ?>>Outflow</option>
            </select>
            <select name="mode" style="width:140px;">
                <option value="">All Modes</option>
                <?php foreach ($modes as $m): ?>
                <option value="<?= sanitize($m) ?>" <?= $modeFilter===$m?'selected':'' ?>><?= sanitize($m) ?></option>
                <?php endforeach; ?>
            </select>
            <input type="text" name="party" value="<?= sanitize($partyFilter) ?>" placeholder="Party name" style="width:140px;">
            <input type="text" name="ref"   value="<?= sanitize($refFilter) ?>"   placeholder="Reference / remarks" style="width:150px;">
            <button class="btn"><?= icon('filter') ?> Apply</button>
        </form>
        <?php $qe = http_build_query(['from'=>$fromDate,'to'=>$toDate,'type'=>$typeFilter,'mode'=>$modeFilter,'party'=>$partyFilter,'ref'=>$refFilter]); ?>
        <a href="?<?= $qe ?>&export=csv"   class="btn"><?= icon('file-type-csv') ?> CSV</a>
        <a href="?<?= $qe ?>&export=excel" class="btn"><?= icon('file-spreadsheet') ?> Excel</a>
        <a href="?<?= $qe ?>&export=pdf"   target="_blank" class="btn"><?= icon('file-type-pdf') ?> PDF</a>
        <button class="btn" onclick="window.print()"><?= icon('printer') ?> Print</button>
    </div>
</div>

<!-- Summary -->
<div class="stat-grid">
    <div class="stat-card success"><div class="stat-label"><?= icon('arrow-down-circle') ?> Total Inflow</div><div class="stat-value"><?= formatMoney($summary['inflow']) ?></div></div>
    <div class="stat-card danger"><div class="stat-label"><?= icon('arrow-up-circle') ?> Total Outflow</div><div class="stat-value"><?= formatMoney($summary['outflow']) ?></div></div>
    <div class="stat-card <?= $net>=0?'primary':'danger' ?>"><div class="stat-label"><?= icon('arrows-exchange') ?> Net Cash Flow</div><div class="stat-value"><?= ($net<0?'- ':'') . formatMoney(abs($net)) ?></div></div>
    <div class="stat-card"><div class="stat-label"><?= icon('list') ?> Transactions</div><div class="stat-value"><?= $summary['transactions'] ?></div></div>
</div>

<!-- All Transactions -->
<div class="card">
    <div class="card-title"><?= icon('list') ?> All Transactions</div>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>Date & Time</th>
                    <th>Type</th>
                    <th>Party</th>
                    <th>Reference</th>
                    <th class="text-right">Amount</th>
                    <th>Mode</th>
                    <th>Remarks</th>
                    <th>Marked By</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($transactions as $i => $t): ?>
            <tr>
                <td><?= $i+1 ?></td>
                <td class="mono text-sm"><?= date('d-M-Y H:i', strtotime($t['payment_date'])) ?></td>
                <td>
                    <span class="badge badge-<?= $t['payment_type']==='inflow'?'success':'danger' ?>">
                        <?= $t['payment_type']==='inflow' ? '↓ INFLOW' : '↑ OUTFLOW' ?>
                    </span>
                </td>
                <td><?= sanitize($t['party_name']) ?></td>
                <td class="text-sm">
                    <span class="badge badge-muted"><?= ucfirst($t['reference_type']) ?></span>
                    #<?= $t['reference_id'] ?>
                </td>
                <td class="num mono <?= $t['payment_type']==='inflow'?'text-success':'text-danger' ?>">
                    <strong><?= formatMoney($t['amount']) ?></strong>
                </td>
                <td class="text-sm"><?= sanitize($t['payment_mode']) ?></td>
                <td class="text-sm text-muted"><?= sanitize(substr($t['remarks'],0,50)) ?></td>
                <td class="text-sm"><?= sanitize($t['marked_by_name'] ?? '-') ?></td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($transactions)): ?>
            <tr><td colspan="9" class="empty-state">No transactions found for this filter.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Date-wise Summary -->
<div class="card">
    <div class="card-title"><?= icon('calendar') ?> Date-wise Summary</div>
    <div class="table-wrap">
        <table>
            <thead><tr><th>Date</th><th class="text-right">Inflow</th><th class="text-right">Outflow</th><th class="text-right">Net</th></tr></thead>
            <tbody>
            <?php foreach ($dateWise as $d):
                $dNet = $d['inflow'] - $d['outflow'];
            ?>
            <tr>
                <td><?= date('d-M-Y (D)', strtotime($d['pdate'])) ?></td>
                <td class="num text-success"><?= formatMoney($d['inflow']) ?></td>
                <td class="num text-danger"><?= formatMoney($d['outflow']) ?></td>
                <td class="num <?= $dNet>=0?'text-success':'text-danger' ?>"><strong><?= ($dNet<0?'- ':'') . formatMoney(abs($dNet)) ?></strong></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
