<?php
require_once __DIR__ . '/includes/admin_bootstrap.php';
$msg = '';
$action = $_GET['action'] ?? 'list';
$editId = (int)($_GET['id'] ?? 0);

/* ── Delete investor ── */
if ($action === 'delete' && $editId) {
    $pdo->prepare("DELETE FROM users WHERE id=? AND role='investor'")->execute([$editId]);
    redirect(BASE_URL . '/admin/investors.php?deleted=1');
}

/* ── Save investor (add/edit) ── */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_investor'])) {
    $name  = trim($_POST['name']  ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $share = (float)($_POST['share_percent'] ?? 0); 
    $pass  = $_POST['password'] ?? '';
    $iid   = (int)($_POST['investor_id'] ?? 0);

    if (!$name || !$phone) {
        $msg = '<div class="alert alert-error">নাম ও ফোন নম্বর আবশ্যক।</div>';
    } else {
        if ($iid) {
            if ($pass) {
                $hash = password_hash($pass, PASSWORD_DEFAULT);
                $pdo->prepare("UPDATE users SET name=?,phone=?,email=?,share_percent=?,password=? WHERE id=? AND role='investor'")
                    ->execute([$name, $phone, $email, (string)$share, $hash, $iid]);
            } else {
                $pdo->prepare("UPDATE users SET name=?,phone=?,email=?,share_percent=? WHERE id=? AND role='investor'")
                    ->execute([$name, $phone, $email, (string)$share, $iid]);
            }
        } else {
            if (!$pass) { $msg = '<div class="alert alert-error">পাসওয়ার্ড আবশ্যক।</div>'; goto endSave; }
            $chk = $pdo->prepare("SELECT id FROM users WHERE phone=?"); $chk->execute([$phone]);
            if ($chk->fetch()) { $msg = '<div class="alert alert-error">এই ফোন নম্বর ইতিমধ্যে ব্যবহৃত।</div>'; goto endSave; }
            $hash = password_hash($pass, PASSWORD_DEFAULT);
            $pdo->prepare("INSERT INTO users (name,phone,email,share_percent,password,role) VALUES (?,?,?,?,?,'investor')")
                ->execute([$name, $phone, $email, (string)$share, $hash]);
        }
        $msg = '<div class="alert alert-success"><i class="fas fa-check-circle"></i> ইনভেস্টর সংরক্ষণ সফল।</div>';
        $action = 'list'; $editId = 0;
    }
    endSave:;
}

/* ── Add transaction ── */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_txn'])) {
    $invId   = (int)$_POST['investor_id_txn'];
    $amount  = (float)$_POST['amount'];
    $note    = trim($_POST['note'] ?? '');
    $date    = $_POST['transaction_date'] ?? date('Y-m-d');
    $txnType = $_POST['txn_type'] ?? 'given';
    $amount  = $txnType === 'taken' ? -abs($amount) : abs($amount);
    $pdo->prepare("INSERT INTO investor_transactions (investor_id,amount,note,transaction_date) VALUES (?,?,?,?)")
        ->execute([$invId, $amount, $note, $date]);
    $msg = '<div class="alert alert-success"><i class="fas fa-check-circle"></i> লেনদেন যোগ হয়েছে।</div>';
}

/* ── Delete transaction ── */
if (isset($_GET['del_txn'])) {
    $pdo->prepare("DELETE FROM investor_transactions WHERE id=?")->execute([(int)$_GET['del_txn']]);
    redirect(BASE_URL . '/admin/investors.php?view=' . ($_GET['view'] ?? 0));
}

/* ── Load investors with balance & share ── */
$investors = $pdo->query(
    "SELECT u.*,
        COALESCE((SELECT SUM(amount) FROM investor_transactions WHERE investor_id=u.id),0) AS balance
     FROM users u WHERE u.role='investor' ORDER BY u.name"
)->fetchAll();

// Total invested across all investors (sum of positive transactions)
$totalInvested = $pdo->query(
    "SELECT COALESCE(SUM(amount),0) FROM investor_transactions WHERE amount > 0"
)->fetchColumn();

// Total given back (negative)
$totalGiven = abs($pdo->query(
    "SELECT COALESCE(SUM(amount),0) FROM investor_transactions WHERE amount < 0"
)->fetchColumn());

// Net balance outstanding
$netBalance = $totalInvested - $totalGiven;

/* ── Share percent total ── */
$totalSharePct = 0;
foreach ($investors as $inv) $totalSharePct += (float)($inv['share_percent'] ?? 0);

/* ── View transactions ── */
$viewInvestor = null;
$transactions = [];
if (isset($_GET['view'])) {
    $vs = $pdo->prepare("SELECT * FROM users WHERE id=? AND role='investor'");
    $vs->execute([(int)$_GET['view']]); $viewInvestor = $vs->fetch();
    if ($viewInvestor) {
        $ts = $pdo->prepare("SELECT * FROM investor_transactions WHERE investor_id=? ORDER BY transaction_date DESC");
        $ts->execute([$viewInvestor['id']]); $transactions = $ts->fetchAll();
    }
}

$editing = null;
if ($editId && $action === 'edit') {
    $es = $pdo->prepare("SELECT * FROM users WHERE id=? AND role='investor'");
    $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 ($viewInvestor): ?>
<!-- ============ TRANSACTION VIEW ============ -->
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;flex-wrap:wrap;gap:10px;">
    <h3 style="color:var(--navy);"><?= e($viewInvestor['name']) ?> — লেনদেন</h3>
    <a href="?" class="topbar-btn btn-gray"><i class="fas fa-arrow-left"></i> ফিরে যান</a>
</div>

<div style="display:grid;grid-template-columns:1fr 320px;gap:24px;align-items:start;">
    <div class="card">
        <div class="card-header"><h3>লেনদেনের ইতিহাস</h3></div>
        <div class="table-wrap">
            <table>
                <thead><tr><th>তারিখ</th><th>পরিমাণ</th><th>ধরন</th><th>নোট</th><th></th></tr></thead>
                <tbody>
                <?php $running = 0; foreach ($transactions as $t): $running += $t['amount']; ?>
                <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="badge badge-approved">প্রদত্ত</span>'
                        : '<span class="badge badge-cancelled">গৃহীত</span>' ?></td>
                    <td><?= e($t['note']) ?></td>
                    <td>
                        <a href="?view=<?= $viewInvestor['id'] ?>&del_txn=<?= $t['id'] ?>"
                           class="topbar-btn btn-red" data-confirm="মুছে ফেলবেন?">
                           <i class="fas fa-trash"></i>
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php $finalBal = array_sum(array_column($transactions,'amount')); ?>
        <div style="padding:14px 24px;display:flex;justify-content:space-between;border-top:1px solid var(--gray-100);font-weight:700;">
            <span>মোট ব্যালেন্স:</span>
            <span style="color:<?= $finalBal>=0?'var(--success)':'var(--danger)' ?>;font-size:1.1rem;">৳<?= number_format($finalBal,2) ?></span>
        </div>
    </div>

    <div class="card">
        <div class="card-header"><h3>নতুন লেনদেন যোগ</h3></div>
        <div class="card-body">
            <form method="POST">
                <input type="hidden" name="investor_id_txn" value="<?= $viewInvestor['id'] ?>">
                <div class="form-group">
                    <label class="form-label">লেনদেনের ধরন</label>
                    <select class="form-control" name="txn_type">
                        <option value="given">ইনভেস্টরকে দেওয়া (+)</option>
                        <option value="taken">ইনভেস্টর থেকে নেওয়া (−)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">পরিমাণ (৳) *</label>
                    <input type="number" class="form-control" name="amount" min="0.01" step="0.01" required>
                </div>
                <div class="form-group">
                    <label class="form-label">তারিখ</label>
                    <input type="date" class="form-control" name="transaction_date" value="<?= date('Y-m-d') ?>">
                </div>
                <div class="form-group">
                    <label class="form-label">নোট</label>
                    <textarea class="form-control" name="note" rows="2" placeholder="লভ্যাংশ, বিনিয়োগ..."></textarea>
                </div>
                <button type="submit" name="add_txn" class="topbar-btn btn-gold" style="width:100%;justify-content:center;">
                    <i class="fas fa-plus"></i> লেনদেন যোগ করুন
                </button>
            </form>
        </div>
    </div>
</div>

<?php else: ?>
<!-- ============ MAIN LIST ============ -->

<!-- Summary Cards -->
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:16px;margin-bottom:24px;">
    <div class="stat-card">
        <div class="stat-icon"><i class="fas fa-hand-holding-usd"></i></div>
        <div class="stat-info">
            <div class="stat-value">৳<?= number_format($totalInvested,2) ?></div>
            <div class="stat-label">মোট বিনিয়োগ প্রাপ্ত</div>
        </div>
    </div>
    <div class="stat-card" style="border-left-color:var(--danger);">
        <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($totalGiven,2) ?></div>
            <div class="stat-label">মোট প্রদান করা হয়েছে</div>
        </div>
    </div>
    <div class="stat-card" style="border-left-color:var(--success);">
        <div class="stat-icon" style="color:var(--success);"><i class="fas fa-balance-scale"></i></div>
        <div class="stat-info">
            <div class="stat-value">৳<?= number_format($netBalance,2) ?></div>
            <div class="stat-label">নিট বকেয়া ব্যালেন্স</div>
        </div>
    </div>
    <div class="stat-card" style="border-left-color:#3182ce;">
        <div class="stat-icon" style="color:#3182ce;"><i class="fas fa-percent"></i></div>
        <div class="stat-info">
            <div class="stat-value"><?= number_format($totalSharePct,1) ?>%</div>
            <div class="stat-label">মোট শেয়ার বিতরণ</div>
        </div>
    </div>
</div>

<div style="display:grid;grid-template-columns:1fr 360px;gap:24px;align-items:start;">

    <!-- Investors Table -->
    <div class="card">
        <div class="card-header">
            <h3>সকল ইনভেস্টর ও শেয়ার</h3>
        </div>
        <div class="table-wrap">
            <table class="share-table">
                <thead><tr>
                    <th>নাম</th>
                    <th>ফোন</th>
                    <th>মোট বিনিয়োগ</th>
                    <th>ব্যালেন্স</th>
                    <th>শেয়ার %</th>
                    <th>অ্যাকশন</th>
                </tr></thead>
                <tbody>
                <?php
                // Per investor: total positive txn = their total investment
                foreach ($investors as $inv):
                    $invTotal = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM investor_transactions WHERE investor_id=? AND amount>0");
                    $invTotal->execute([$inv['id']]);
                    $invTotalAmt = (float)$invTotal->fetchColumn();
                    $sharePct = (float)($inv['share_percent'] ?? 0);
                    $balColor = $inv['balance'] >= 0 ? 'var(--success)' : 'var(--danger)';
                ?>
                <tr>
                    <td><strong><?= e($inv['name']) ?></strong></td>
                    <td><?= e($inv['phone']) ?></td>
                    <td style="font-weight:700;">৳<?= number_format($invTotalAmt,2) ?></td>
                    <td style="font-weight:700;color:<?= $balColor ?>;">
                        <?= $inv['balance']>=0?'+':'' ?>৳<?= number_format(abs($inv['balance']),2) ?>
                    </td>
                    <td>
                        <div style="display:flex;align-items:center;gap:8px;">
                            <div class="progress-bar-wrap" style="min-width:60px;">
                                <div class="progress-bar" style="width:<?= min(100,$sharePct) ?>%;"></div>
                            </div>
                            <span style="font-weight:700;color:var(--navy);min-width:36px;"><?= number_format($sharePct,1) ?>%</span>
                        </div>
                    </td>
                    <td>
                        <div class="actions">
                            <a href="?view=<?= $inv['id'] ?>" class="topbar-btn btn-navy"><i class="fas fa-exchange-alt"></i> লেনদেন</a>
                            <a href="?action=edit&id=<?= $inv['id'] ?>" class="topbar-btn btn-gray"><i class="fas fa-edit"></i></a>
                            <a href="?action=delete&id=<?= $inv['id'] ?>" class="topbar-btn btn-red" data-confirm="এই ইনভেস্টর মুছে ফেলবেন?"><i class="fas fa-trash"></i></a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
                <?php if (!empty($investors)): ?>
                <tfoot>
                    <tr style="background:var(--gray-100);">
                        <td colspan="2"><strong>মোট</strong></td>
                        <td><strong>৳<?= number_format($totalInvested,2) ?></strong></td>
                        <td><strong>৳<?= number_format($netBalance,2) ?></strong></td>
                        <td><strong><?= number_format($totalSharePct,1) ?>%</strong>
                            <?php if ($totalSharePct < 100): ?>
                                <span style="color:var(--g600);font-size:.78rem;">(<?= number_format(100-$totalSharePct,1) ?>% বাকি)</span>
                            <?php endif; ?>
                        </td>
                        <td></td>
                    </tr>
                </tfoot>
                <?php endif; ?>
            </table>
        </div>
    </div>

    <!-- Add/Edit Form -->
    <div class="card">
        <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="investor_id" value="<?= $editing['id'] ?? 0 ?>">
                <div class="form-group">
                    <label class="form-label">নাম *</label>
                    <input type="text" class="form-control" name="name" value="<?= e($editing['name'] ?? '') ?>" required>
                </div>
                <div class="form-group">
                    <label class="form-label">ফোন নম্বর *</label>
                    <input type="tel" class="form-control" name="phone" value="<?= e($editing['phone'] ?? '') ?>" required>
                </div>
                <div class="form-group">
                    <label class="form-label">ইমেইল</label>
                    <input type="email" class="form-control" name="email" value="<?= e($editing['email'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label class="form-label">শেয়ার % <span style="color:var(--g600);font-size:.82rem;">(মোট ১০০% এর মধ্যে)</span></label>
                    <div style="position:relative;">
                        <input type="number" class="form-control" name="share_percent"
                               value="<?= (float)($editing['share_percent'] ?? 0) ?>"
                               min="0" max="100" step="0.1"
                               style="padding-right:36px;">
                        <span style="position:absolute;right:12px;top:50%;transform:translateY(-50%);color:var(--g600);font-weight:700;">%</span>
                    </div>
                    <?php if (!empty($investors)): ?>
                    <div class="form-hint">বর্তমান মোট বিতরণ: <?= number_format($totalSharePct,1) ?>%
                        <?php if (!$editing): ?>
                            | বাকি: <?= number_format(max(0,100-$totalSharePct),1) ?>%
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="form-group">
                    <label class="form-label">পাসওয়ার্ড <?= $editing ? '(পরিবর্তন না করলে ফাঁকা)' : '*' ?></label>
                    <input type="password" class="form-control" name="password" <?= $editing ? '' : 'required' ?>>
                </div>
                <button type="submit" name="save_investor" class="topbar-btn btn-gold" style="width:100%;justify-content:center;">
                    <i class="fas fa-save"></i> সংরক্ষণ করুন
                </button>
            </form>
        </div>
    </div>
</div>

<?php endif; ?>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
