<?php

include "../includes/member_auth.php";
include "../config/database.php";

$sql = "SELECT * FROM users WHERE id = ?";

$stmt = $pdo->prepare($sql);

$stmt->execute([$_SESSION['user_id']]);

$user = $stmt->fetch(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| MEMBER UNPAID DEFAULTS
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT
        COALESCE(SUM(amount), 0) AS total_default,
        COUNT(*) AS missed_payments
    FROM subscription_defaults
    WHERE user_id = ?
    AND status = 'unpaid'
");

$stmt->execute([
    $_SESSION['user_id']
]);

$defaultData = $stmt->fetch(PDO::FETCH_ASSOC);

$totalDefault = (float)($defaultData['total_default'] ?? 0);

$missedPayments = (int)($defaultData['missed_payments'] ?? 0);

/*
|--------------------------------------------------------------------------
| RECENT WALLET TRANSACTIONS
|--------------------------------------------------------------------------
*/

$sql = "SELECT *
        FROM wallet_transactions
        WHERE user_id = ?
        ORDER BY created_at DESC
        LIMIT 5";

$stmt = $pdo->prepare($sql);

$stmt->execute([$_SESSION['user_id']]);

$transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| AVAILABLE PLANS
|--------------------------------------------------------------------------
*/

$sql = "SELECT *
        FROM plans
        WHERE status='active'
        ORDER BY id DESC";

$stmt = $pdo->prepare($sql);

$stmt->execute();

$plans = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stmt = $pdo->prepare("
SELECT *
FROM plans
WHERE status='active'
ORDER BY id DESC
LIMIT 3
");

$stmt->execute();

$plans = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Member Dashboard</title>

<link rel="stylesheet" href="../assets/css/admin.css">

<link rel="stylesheet" href="../assets/css/responsive.css">

<link rel="stylesheet" href="../assets/css/member.css">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css">

</head>

<body>

<?php include "../includes/member_sidebar.php"; ?>

<div class="sidebar-overlay"></div>

<?php include "../includes/member_topbar.php"; ?>

<div class="main-content">

<div class="page-title">

    <h1>Welcome Back 👋</h1>

    <p><?php echo htmlspecialchars($user['fullname']); ?></p>

</div>

<div class="dashboard-grid">

    <div class="dashboard-card">

        <div class="card-icon wallet">

            <i class="fas fa-wallet"></i>

        </div>

        <h4>Wallet Balance</h4>

        <h2>₦<?php echo number_format($user['wallet_balance'],2); ?></h2>

    </div>

    <div class="dashboard-card">

        <div class="card-icon bank">

            <i class="fas fa-building-columns"></i>

        </div>

        <h4>Virtual Account</h4>

        <p>

        <?php

        if(empty($user['virtual_account_number'])){

            echo "Pending";

        }else{

            echo $user['virtual_account_number'];

        }

        ?>

        </p>

    </div>

<div class="dashboard-card">

    <div class="card-icon target">

        <i class="fas fa-triangle-exclamation"></i>

    </div>

    <h4>Default</h4>

    <h2>
        ₦<?= number_format($totalDefault, 2); ?>
    </h2>

    <p>

        <?php if ($missedPayments > 0): ?>

            <?= $missedPayments; ?>

            <?= $missedPayments === 1
                ? 'Missed Payment'
                : 'Missed Payments'; ?>

        <?php else: ?>

            No Missed Payments

        <?php endif; ?>

    </p>

    <a
    href="defaults.php"
    style="
        display:inline-block;
        margin-top:10px;
        font-size:12px;
        font-weight:600;
        color:#2563eb;
        text-decoration:none;
    "
>
    View Defaults
    <i class="fas fa-arrow-right"></i>
</a>

</div>

    <div class="dashboard-card">

        <div class="card-icon scheme">

            <i class="fas fa-layer-group"></i>

        </div>

        <h4>Active Schemes</h4>

        <h2><?php

$stmt = $pdo->prepare("
SELECT COUNT(*)
FROM subscriptions
WHERE user_id=?
AND status='active'
");

$stmt->execute([$_SESSION['user_id']]);

?>

<h2><?= $stmt->fetchColumn(); ?></h2></h2>

    </div>

</div>


<div class="dashboard-bottom">

    <div class="activity-card">

<div class="activity-header-bar">

    <div class="activity-title-wrap">

        <i class="fas fa-clock-rotate-left"></i>

        <h3>Recent Activities</h3>

    </div>

    <a href="history.php" class="activity-view-link">

        View All <i class="fas fa-arrow-right"></i>

    </a>

</div>

        <div class="activity-list">

        <?php if(count($transactions) > 0): ?>

<?php foreach($transactions as $transaction): ?>

<div class="activity-item">

    <div class="activity-icon success">

        <i class="fas fa-wallet"></i>

    </div>

    <div class="activity-details">

        <h4><?= ucfirst($transaction['transaction_type']); ?></h4>

        <p><?= htmlspecialchars($transaction['description']); ?></p>

    </div>

    <span>

        ₦<?= number_format($transaction['amount'],2); ?>

    </span>

</div>

<?php endforeach; ?>

<?php else: ?>

<div class="activity-item">

    <div class="activity-icon pending">

        <i class="fas fa-wallet"></i>

    </div>

    <div class="activity-details">

        <h4>No Transactions Yet</h4>

        <p>Your wallet has not been funded yet.</p>

    </div>

    <span>--</span>

</div>

<?php endif; ?>  

        </div>

    </div>

</div>

<div class="available-plans">

<div class="section-header">

    <h3>
        🔥 Popular Schemes
    </h3>

    <a href="schemes.php" class="view-all">
        View All <i class="fas fa-arrow-right"></i>
    </a>

</div>

<div class="plans-grid">

<?php if(count($plans)>0): ?>

<?php foreach($plans as $plan): ?>

<?php

$check = $pdo->prepare("
SELECT hands
FROM subscriptions
WHERE user_id=?
AND plan_id=?
AND status='active'
LIMIT 1
");

$check->execute([
    $_SESSION['user_id'],
    $plan['id']
]);

$joined = $check->fetch(PDO::FETCH_ASSOC);

?>

<div class="plan-card">

<div class="plan-top">

<div class="plan-icon">

<i class="fas fa-piggy-bank"></i>

</div>

<div>

<h4><?= htmlspecialchars($plan['plan_name']); ?></h4>

<div class="plan-frequency">

📅 <?= htmlspecialchars($plan['frequency']); ?>

&nbsp;&nbsp;•&nbsp;&nbsp;

⏳ <?= htmlspecialchars($plan['duration']); ?>

</div>

</div>

</div>

<div class="plan-price">

₦<?= number_format($plan['amount'],2); ?>

</div>

<div class="per-hand">

Per Hand

</div>

<div class="plan-description">

<?= htmlspecialchars($plan['description']); ?>

</div>

<?php if($joined): ?>

<button class="fund-wallet-btn joined-btn" disabled>

✅ Already Joined (<?= $joined['hands']; ?> Hands)

</button>

<?php else: ?>

<a href="join_plan.php?id=<?= $plan['id']; ?>" class="fund-wallet-btn">

Join Scheme

</a>

<?php endif; ?>

</div>

<?php endforeach; ?>

<?php else: ?>

<p>No active schemes available.</p>

<?php endif; ?>

</div>

</div>

<div class="quick-actions">

    <h3>Quick Actions</h3>

    <div class="quick-grid">

        <a href="wallet.php" class="quick-card">

            <i class="fas fa-wallet"></i>

            <span>Fund Wallet</span>

        </a>

        <a href="schemes.php" class="quick-card">

            <i class="fas fa-layer-group"></i>

            <span>Join Scheme</span>

        </a>

        <a href="history.php" class="quick-card">

            <i class="fas fa-clock-rotate-left"></i>

            <span>Transactions</span>

        </a>

        <a href="profile.php" class="quick-card">

            <i class="fas fa-user"></i>

            <span>My Profile</span>

        </a>

    </div>

</div>

</div>

<script src="../assets/js/admin.js"></script>


<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<?php if(isset($_SESSION['success'])): ?>

<script>

document.addEventListener("DOMContentLoaded", function(){

    Swal.fire({

        icon:'success',

        title:'Congratulations!',

        html: <?= json_encode($_SESSION['success']); ?>,

        confirmButtonColor:'#0D6EFD'

    });

});

</script>

<?php unset($_SESSION['success']); endif; ?>

<?php if(isset($_SESSION['error'])): ?>

<script>

document.addEventListener("DOMContentLoaded", function(){

    Swal.fire({

        icon:'error',

        title:'Oops...',

        text: <?= json_encode($_SESSION['error']); ?>,

        confirmButtonColor:'#dc3545'

    });

});

</script>

<?php unset($_SESSION['error']); endif; ?>

</body>

</html>