<?php

session_start();

if (!isset($_SESSION['logged_in'])) {

    header("Location: ../login.php");
    exit();

}

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

$userId = $_SESSION['user_id'];

$amount = trim($_POST['amount']);
$type = trim($_POST['contribution_type']);


if (empty($amount) || empty($type)) {

    $_SESSION['error'] = "Please complete the form.";

    header("Location: ../member/contributions.php");
    exit();

}

if ($amount <= 0) {

    $_SESSION['error'] = "Invalid contribution amount.";

    header("Location: ../member/contributions.php");
    exit();

}
// Save contribution

$sql = "INSERT INTO contributions
(user_id, amount, contribution_type)
VALUES (?, ?, ?)";

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

$stmt->execute([
    $userId,
    $amount,
    $type
]);

// Update user's total savings and contributions

$sql = "UPDATE users
SET
    total_savings = total_savings + ?,
    total_contributions = total_contributions + ?
WHERE id = ?";

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

$stmt->execute([
    $amount,
    $amount,
    $userId
]);

$_SESSION['success'] = "Contribution added successfully.";

header("Location: ../member/contributions.php");
exit();