<?php
require_once __DIR__.'/config/database.php';
$settings=getAllSettings($pdo);
requireInvestor();

$userId=$_SESSION['user_id'];
$tab=$_GET['tab']??'stock';

$userStmt=$pdo->prepare("SELECT * FROM users WHERE id=?");
$userStmt->execute([$userId]);
$user=$userStmt->fetch();

// Transactions
$txnStmt=$pdo->prepare("SELECT * FROM investor_transactions WHERE investor_id=? ORDER BY transaction_date DESC");
$txnStmt->execute([$userId]);
$transactions=$txnStmt->fetchAll();
$balance=array_sum(array_column($transactions,'amount'));
$totalGiven=array_sum(array_filter(array_column($transactions,'amount'),fn($a)=>$a>0));

// Products
$products=$pdo->query("SELECT p.*,c.name as cat_name FROM products p LEFT JOIN categories c ON p.category_id=c.id ORDER BY p.name ASC")->fetchAll();

// Expenses
$expenses=$pdo->query("SELECT * FROM expenses ORDER BY expense_date DESC LIMIT 100")->fetchAll();
$totalExpenses=$pdo->query("SELECT COALESCE(SUM(amount),0) FROM expenses")->fetchColumn();

$sharePct=(float)($user['share_percent']??0);

$navItems=[
    ['tab'=>'stock',        'icon'=>'fa-boxes',              'label'=>'স্টক'],
    ['tab'=>'transactions', 'icon'=>'fa-exchange-alt',       'label'=>'লেনদেন'],
    ['tab'=>'expenses',     'icon'=>'fa-file-invoice-dollar','label'=>'ব্যয়'],
];

include __DIR__.'/includes/header.php';
?>

<style>
.dash-page{padding:24px 0 56px}
.dash-grid{display:grid;grid-template-columns:1fr;gap:20px}
@media(min-width:820px){.dash-grid{grid-template-columns:220px 1fr;gap:24px}}
.dash-tabbar{display:flex;overflow-x:auto;gap:0;background:var(--navy);border-radius:var(--r-lg);scrollbar-width:none;margin-bottom:18px}
.dash-tabbar::-webkit-scrollbar{display:none}
.dash-tab{display:flex;flex-direction:column;align-items:center;gap:4px;padding:12px 14px;color:rgba(255,255,255,.6);font-size:.75rem;font-weight:500;cursor:pointer;border-bottom:3px solid transparent;white-space:nowrap;transition:all .2s;flex:1;min-width:72px;text-decoration:none}
.dash-tab:hover,.dash-tab.active{color:var(--gold);border-bottom-color:var(--gold);background:rgba(212,175,55,.07)}
.dash-tab i{font-size:1.1rem}
@media(min-width:820px){.dash-tabbar{display:none}}
.dash-sidebar{background:var(--navy);border-radius:var(--r-lg);display:none;position:sticky;top:80px;height:fit-content}
@media(min-width:820px){.dash-sidebar{display:block}}
.ds-user{padding:20px 18px 16px;border-bottom:1px solid rgba(255,255,255,.1);margin-bottom:4px}
.ds-avatar{width:52px;height:52px;background:var(--gold);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1.3rem;color:var(--navy);font-weight:700;margin-bottom:8px}
.ds-name{color:#fff;font-weight:700;font-size:.93rem}
.ds-role{color:rgba(255,255,255,.45);font-size:.78rem}
.ds-nav a{display:flex;align-items:center;gap:10px;padding:11px 18px;color:rgba(255,255,255,.68);font-size:.88rem;font-weight:500;transition:all .2s;border-left:3px solid transparent}
.ds-nav a:hover,.ds-nav a.active{color:var(--gold);background:rgba(212,175,55,.08);border-left-color:var(--gold)}
.ds-nav a i{width:16px;text-align:center}
.ds-share{background:rgba(212,175,55,.12);border-radius:var(--r);padding:12px 18px;margin:12px 14px 4px;text-align:center}
.ds-share .share-pct{font-size:1.8rem;font-weight:700;color:var(--gold)}
.ds-share .share-label{font-size:.75rem;color:rgba(255,255,255,.5);margin-top:2px}
.dash-content-card{background:#fff;border-radius:var(--r-lg);padding:18px;box-shadow:var(--sh);margin-bottom:18px}
@media(min-width:600px){.dash-content-card{padding:24px}}
.dash-content-card h3{font-size:1.05rem;font-weight:700;color:var(--navy);margin-bottom:16px;padding-bottom:10px;border-bottom:2px solid var(--g100)}
.inv-stat-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:20px}
@media(min-width:600px){.inv-stat-grid{grid-template-columns:repeat(4,1fr)}}
.inv-stat{background:#fff;border-radius:var(--r);padding:14px;box-shadow:var(--sh);border-left:4px solid var(--gold);text-align:center}
.inv-stat .sv{font-size:1.2rem;font-weight:700;color:var(--navy)}
@media(min-width:600px){.inv-stat .sv{font-size:1.5rem}}
.inv-stat .sl{font-size:.75rem;color:var(--g600);margin-top:3px}
</style>

<div class="dash-page">
<div class="container">

    <!-- Summary stats (always visible) -->
    <div class="inv-stat-grid">
        <div class="inv-stat" style="border-left-color:var(--gold);">
            <div class="sv">৳<?=number_format(abs($balance),2)?></div>
            <div class="sl">আমার ব্যালেন্স</div>
        </div>
        <div class="inv-stat" style="border-left-color:#3182ce;">
            <div class="sv"><?=number_format($sharePct,1)?>%</div>
            <div class="sl">আমার শেয়ার</div>
        </div>
        <div class="inv-stat" style="border-left-color:var(--success);">
            <div class="sv">৳<?=number_format($totalGiven,2)?></div>
            <div class="sl">মোট বিনিয়োগ</div>
        </div>
        <div class="inv-stat" style="border-left-color:var(--danger);">
            <div class="sv">৳<?=number_format($totalExpenses,2)?></div>
            <div class="sl">মোট ব্যয়</div>
        </div>
    </div>

    <!-- Mobile Tab Bar -->
    <div class="dash-tabbar">
        <?php foreach($navItems as $ni): ?>
        <a href="?tab=<?=$ni['tab']?>" class="dash-tab <?=$tab===$ni['tab']?'active':''?>">
            <i class="fas <?=$ni['icon']?>"></i><?=$ni['label']?>
        </a>
        <?php endforeach; ?>
        <a href="<?=BASE_URL?>/logout.php" class="dash-tab" style="color:#e88;">
            <i class="fas fa-sign-out-alt"></i>লগআউট
        </a>
    </div>

    <div class="dash-grid">

        <!-- Desktop Sidebar -->
        <div class="dash-sidebar">
            <div class="ds-user">
                <div class="ds-avatar"><?=mb_substr($user['name'],0,1)?></div>
                <div class="ds-name"><?=e($user['name'])?></div>
                <div class="ds-role">ইনভেস্টর</div>
            </div>
            <!-- Share % display -->
            <div class="ds-share">
                <div class="share-pct"><?=number_format($sharePct,1)?>%</div>
                <div class="share-label">আমার শেয়ার</div>
            </div>
            <nav class="ds-nav" style="padding-top:8px;">
                <?php foreach($navItems as $ni): ?>
                <a href="?tab=<?=$ni['tab']?>" class="<?=$tab===$ni['tab']?'active':''?>">
                    <i class="fas <?=$ni['icon']?>"></i><?=$ni['label']?>
                </a>
                <?php endforeach; ?>
                <a href="<?=BASE_URL?>/logout.php" style="color:#e53e3e!important;">
                    <i class="fas fa-sign-out-alt"></i>লগআউট
                </a>
            </nav>
        </div>

        <!-- Content -->
        <div>

            <?php if($tab==='stock'): ?>
            <div class="dash-content-card">
                <h3>পণ্যের স্টক (শুধুমাত্র দেখার জন্য)</h3>
                <div style="overflow-x:auto;">
                    <table style="min-width:440px;">
                        <thead><tr><th>পণ্যের নাম</th><th>ক্যাটেগরি</th><th>মূল্য</th><th>স্টক</th><th>অবস্থা</th></tr></thead>
                        <tbody>
                        <?php foreach($products as $p): ?>
                        <tr>
                            <td><?=e($p['name'])?></td>
                            <td><?=e($p['cat_name']??'-')?></td>
                            <td>৳<?=number_format($p['price'],2)?></td>
                            <td><?=$p['stock']?></td>
                            <td>
                                <?php if($p['stock']<=0): ?>
                                    <span class="status-badge status-cancelled">স্টক নেই</span>
                                <?php elseif($p['stock']<=5): ?>
                                    <span class="status-badge status-pending">কম (<?=$p['stock']?>)</span>
                                <?php else: ?>
                                    <span class="status-badge status-delivered">পর্যাপ্ত</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <?php elseif($tab==='transactions'): ?>
            <div class="dash-content-card">
                <h3>লেনদেনের ইতিহাস</h3>
                <div style="display:flex;gap:12px;flex-wrap:wrap;margin-bottom:18px;">
                    <div style="background:<?=$balance>=0?'rgba(56,161,105,.1)':'rgba(229,62,62,.1)'?>;padding:12px 18px;border-radius:var(--r);flex:1;min-width:140px;">
                        <div style="font-size:.78rem;color:var(--g600);">বর্তমান ব্যালেন্স</div>
                        <div style="font-size:1.4rem;font-weight:700;color:<?=$balance>=0?'var(--success)':'var(--danger)'?>;">
                            <?=$balance>=0?'+':''?>৳<?=number_format(abs($balance),2)?>
                        </div>
                    </div>
                    <div style="background:rgba(49,130,206,.08);padding:12px 18px;border-radius:var(--r);flex:1;min-width:140px;">
                        <div style="font-size:.78rem;color:var(--g600);">শেয়ার</div>
                        <div style="font-size:1.4rem;font-weight:700;color:#3182ce;"><?=number_format($sharePct,1)?>%</div>
                    </div>
                </div>
                <?php if(empty($transactions)): ?>
                    <p style="color:var(--g400);text-align:center;padding:24px 0;">কোনো লেনদেন নেই।</p>
                <?php else: ?>
                    <div style="overflow-x:auto;">
                        <table style="min-width:400px;">
                            <thead><tr><th>তারিখ</th><th>পরিমাণ</th><th>ধরন</th><th>নোট</th></tr></thead>
                            <tbody>
                            <?php foreach($transactions as $t): ?>
                            <tr>
                                <td><?=date('d/m/Y',strtotime($t['transaction_date']))?></td>
                                <td style="font-weight:700;color:<?=$t['amount']>=0?'var(--success)':'var(--danger)'?>;">
                                    <?=$t['amount']>=0?'+':''?>৳<?=number_format(abs($t['amount']),2)?>
                                </td>
                                <td><?=$t['amount']>=0
                                    ?'<span class="status-badge status-delivered">প্রদত্ত</span>'
                                    :'<span class="status-badge status-cancelled">গৃহীত</span>'?></td>
                                <td><?=e($t['note']??'')?></td>
                            </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>

            <?php elseif($tab==='expenses'): ?>
            <div class="dash-content-card">
                <h3>ব্যয়সমূহ (শুধুমাত্র দেখার জন্য)</h3>
                <div style="background:rgba(229,62,62,.07);padding:12px 16px;border-radius:var(--r);margin-bottom:16px;font-weight:600;">
                    মোট ব্যয়: <span style="color:var(--danger);">৳<?=number_format($totalExpenses,2)?></span>
                </div>
                <?php if(empty($expenses)): ?>
                    <p style="color:var(--g400);text-align:center;padding:24px 0;">কোনো ব্যয় নেই।</p>
                <?php else: ?>
                    <div style="overflow-x:auto;">
                        <table style="min-width:440px;">
                            <thead><tr><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><?=e($exp['title'])?></td>
                                <td><?=e($exp['category']??'-')?></td>
                                <td style="font-weight:700;color:var(--danger);">৳<?=number_format($exp['amount'],2)?></td>
                                <td style="font-size:.82rem;color:var(--g600);"><?=e(mb_substr($exp['note']??'',0,50))?></td>
                            </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>

            <?php endif; ?>
        </div><!-- /content -->
    </div><!-- /dash-grid -->
</div><!-- /container -->
</div><!-- /dash-page -->

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