<?php
require_once __DIR__ . '/includes/admin_bootstrap.php';

$action = $_GET['action'] ?? 'list';
$editId = (int)($_GET['id'] ?? 0);
$msg    = '';

if ($action === 'delete' && $editId) {
    $pdo->prepare("DELETE FROM expenses WHERE id=?")->execute([$editId]);
    redirect(BASE_URL.'/admin/expenses.php?deleted=1');
}

if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_expense'])) {
    $title  = trim($_POST['title']    ?? '');
    $cat    = trim($_POST['category'] ?? '');
    $amount = (float)($_POST['amount']       ?? 0);
    $date   = $_POST['expense_date']   ?? date('Y-m-d');
    $note   = trim($_POST['note']     ?? '');
    $eid    = (int)($_POST['expense_id'] ?? 0);
    if (!$title || $amount <= 0) {
        $msg = '<div class="alert alert-error">বিষয় ও পরিমাণ আবশ্যক।</div>';
    } else {
        if ($eid) {
            $pdo->prepare("UPDATE expenses SET title=?,category=?,amount=?,expense_date=?,note=? WHERE id=?")->execute([$title,$cat,$amount,$date,$note,$eid]);
        } else {
            $pdo->prepare("INSERT INTO expenses (title,category,amount,expense_date,note) VALUES(?,?,?,?,?)")->execute([$title,$cat,$amount,$date,$note]);
        }
        redirect(BASE_URL.'/admin/expenses.php?saved=1');
    }
}

$expenses       = $pdo->query("SELECT * FROM expenses ORDER BY expense_date DESC")->fetchAll();
$totalExpenses  = array_sum(array_column($expenses,'amount'));
$catTotals      = $pdo->query("SELECT category,SUM(amount) as total FROM expenses GROUP BY category ORDER BY total DESC")->fetchAll();
$editing        = null;
if ($editId && $action==='edit') {
    $es=$pdo->prepare("SELECT * FROM expenses WHERE id=?"); $es->execute([$editId]); $editing=$es->fetch();
}


// ── HTML output starts ──
include __DIR__ . '/includes/admin_header.php';

?>
<h2>ব্যয় ব্যবস্থাপনা</h2>
<?= $msg ?>
<?php if(isset($_GET['deleted'])): ?><div class="alert alert-success"><i class="fas fa-check-circle"></i> মুছে ফেলা হয়েছে।</div><?php endif; ?>
<?php if(isset($_GET['saved'])): ?><div class="alert alert-success"><i class="fas fa-check-circle"></i> সংরক্ষণ সফল।</div><?php endif; ?>

<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:14px;margin-bottom:20px;">
    <div class="stat-card"><div class="stat-icon" style="color:var(--danger);"><i class="fas fa-money-bill-wave"></i></div><div class="stat-info"><div class="stat-value">৳<?=number_format($totalExpenses,2)?></div><div class="stat-label">মোট ব্যয়</div></div></div>
    <div class="stat-card"><div class="stat-icon"><i class="fas fa-list"></i></div><div class="stat-info"><div class="stat-value"><?=count($expenses)?></div><div class="stat-label">মোট এন্ট্রি</div></div></div>
    <div class="stat-card"><div class="stat-icon"><i class="fas fa-tags"></i></div><div class="stat-info"><div class="stat-value"><?=count($catTotals)?></div><div class="stat-label">ক্যাটেগরি</div></div></div>
</div>

<div style="display:grid;grid-template-columns:1fr 360px;gap:24px;align-items:start;">
    <div class="card">
        <div class="card-header"><h3>সকল ব্যয়</h3><a href="?action=add" class="topbar-btn btn-gold"><i class="fas fa-plus"></i> নতুন</a></div>
        <div class="table-wrap">
            <table>
                <thead><tr><th>তারিখ</th><th>বিষয়</th><th>ক্যাটেগরি</th><th>পরিমাণ</th><th>নোট</th><th></th></tr></thead>
                <tbody>
                <?php foreach($expenses as $exp): ?>
                <tr>
                    <td><?=date('d/m/Y',strtotime($exp['expense_date']))?></td>
                    <td><strong><?=e($exp['title'])?></strong></td>
                    <td><?=e($exp['category']??'-')?></td>
                    <td style="font-weight:700;color:var(--danger);">৳<?=number_format($exp['amount'],2)?></td>
                    <td style="font-size:.81rem;color:var(--g600);"><?=e(mb_substr($exp['note']??'',0,40))?></td>
                    <td><div class="actions">
                        <a href="?action=edit&id=<?=$exp['id']?>" class="topbar-btn btn-navy"><i class="fas fa-edit"></i></a>
                        <a href="?action=delete&id=<?=$exp['id']?>" class="topbar-btn btn-red" data-confirm="মুছবেন?"><i class="fas fa-trash"></i></a>
                    </div></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <div>
        <div class="card" style="margin-bottom:16px;">
            <div class="card-header"><h3><?=$editing?'সম্পাদনা':'নতুন ব্যয়'?></h3><?php if($editing): ?><a href="?" class="topbar-btn btn-gray">বাতিল</a><?php endif; ?></div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="expense_id" value="<?=$editing['id']??0?>">
                    <div class="form-group"><label class="form-label">বিষয় *</label><input type="text" class="form-control" name="title" value="<?=e($editing['title']??'')?>" placeholder="বিজ্ঞাপন, বেতন..." required></div>
                    <div class="form-group"><label class="form-label">ক্যাটেগরি</label><input type="text" class="form-control" name="category" value="<?=e($editing['category']??'')?>" list="expCats">
                        <datalist id="expCats"><?php foreach($catTotals as $ct): ?><option value="<?=e($ct['category'])?>"><?php endforeach; ?></datalist></div>
                    <div class="form-group"><label class="form-label">পরিমাণ (৳) *</label><input type="number" class="form-control" name="amount" value="<?=$editing['amount']??''?>" min="0" step="0.01" required></div>
                    <div class="form-group"><label class="form-label">তারিখ</label><input type="date" class="form-control" name="expense_date" value="<?=$editing['expense_date']??date('Y-m-d')?>"></div>
                    <div class="form-group"><label class="form-label">নোট</label><textarea class="form-control" name="note" rows="2"><?=e($editing['note']??'')?></textarea></div>
                    <button type="submit" name="save_expense" class="topbar-btn btn-gold"><i class="fas fa-save"></i> সংরক্ষণ</button>
                </form>
            </div>
        </div>
        <?php if($catTotals): ?>
        <div class="card"><div class="card-header"><h3>ক্যাটেগরি অনুযায়ী</h3></div><div class="card-body" style="padding:14px;">
            <?php foreach($catTotals as $ct): ?>
            <div style="display:flex;justify-content:space-between;padding:7px 0;border-bottom:1px solid var(--g100);">
                <span><?=e($ct['category']??'অন্যান্য')?></span>
                <strong style="color:var(--danger);">৳<?=number_format($ct['total'],2)?></strong>
            </div>
            <?php endforeach; ?>
        </div></div>
        <?php endif; ?>
    </div>
</div>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
