<?php
include '../connection.php';

session_start(); // Ensure session is started

if (!isset($_SESSION['userid'])) {
    if (isset($_COOKIE['userid'])) {
        $_SESSION['userid'] = $_COOKIE['userid'];
    } else {
        header("Location: ../login.php");
        exit();
    }
}

// Handle deposit request
if (isset($_POST['btn_deposit'])) {
    $userid = $_SESSION['userid']; // Sender ID
    $amount = $_POST['amount'];
    $duration = $_POST['duration'];
    $pin = $_POST['pin'];
    $status = "Saved";
    $entry_date = date('Y-m-d');

    // Define an associative array for duration mapping
    $durationMapping = [
        '1' => '+1 month',
        '6' => '+6 months',
        '12' => '+1 year'
    ];

    // Calculate the ending date based on the selected duration
    $ending_date = isset($durationMapping[$duration]) 
        ? date('Y-m-d', strtotime($durationMapping[$duration], strtotime($entry_date))) 
        : $entry_date; // Fallback to entry_date if duration is invalid

    // Check the balance for the user
    $sqlCheckBalance = "SELECT amount FROM balance WHERE userid = ?";
    $stmtCheckBalance = $con->prepare($sqlCheckBalance);
    $stmtCheckBalance->bind_param("i", $userid);
    $stmtCheckBalance->execute();
    $stmtCheckBalance->bind_result($balance);
    $stmtCheckBalance->fetch();
    $stmtCheckBalance->close();

    // Check the PIN from the student table
    $sqlCheckPin = "SELECT pin FROM student WHERE userid = ?";
    $stmtCheckPin = $con->prepare($sqlCheckPin);
    $stmtCheckPin->bind_param("i", $userid);
    $stmtCheckPin->execute();
    $stmtCheckPin->bind_result($storedPin);
    $stmtCheckPin->fetch();
    $stmtCheckPin->close();

    // Validate the conditions
    if ($balance >= $amount) {
        if ($storedPin === $pin) {
            // Prepare the SQL statement to insert into the money_saving table
            $sqlInsertTopup = "INSERT INTO money_saving (userid, amount, duration, entry_date, ending_date, status) VALUES (?, ?, ?, ?, ?, ?)";
            $stmtInsertTopup = $con->prepare($sqlInsertTopup);
            $stmtInsertTopup->bind_param("isssss", $userid, $amount, $duration, $entry_date, $ending_date, $status);
            $stmtInsertTopup->execute();

            // Deduct the amount from sender's balance
            $sqlDeductBalance = "UPDATE balance SET amount = amount - ? WHERE userid = ?";
            $stmtDeductBalance = $con->prepare($sqlDeductBalance);
            $stmtDeductBalance->bind_param("si", $amount, $userid);
            $stmtDeductBalance->execute();

            $_SESSION['message'] = "রিকোয়েস্ট সফল হয়েছে"; // Request successful
            $stmtInsertTopup->close();
        } else {
            $_SESSION['message'] = "আপনার পিন নম্বর সঠিক নয়"; // Your PIN number is incorrect
        }
    } else {
        $_SESSION['message'] = "আপনার অ্যাকাউন্টে পর্যাপ্ত টাকা নেই"; // You do not have sufficient balance in your account
    }
	
	header("Location: index.php");
    exit();
}

// Handle withdrawal request
if (isset($_POST['btn_withdraw'])) {
    $savingId = $_POST['SavingId']; // Get the saving ID
    $userid = $_SESSION['userid']; // Sender ID

    // Check the saving record based on the ID
    $sqlCheckSaving = "SELECT amount, ending_date, status FROM money_saving WHERE id = ? AND userid = ?";
    $stmtCheckSaving = $con->prepare($sqlCheckSaving);
    $stmtCheckSaving->bind_param("ii", $savingId, $userid);
    $stmtCheckSaving->execute();
    $stmtCheckSaving->bind_result($savedAmount, $endingDate, $status);
    $stmtCheckSaving->fetch();
    $stmtCheckSaving->close();

    // Check eligibility for withdrawal
    if ($status === 'Saved' && (date('Y-m-d') >= $endingDate)) {
        // Update status to Claimed
        $sqlUpdateStatus = "UPDATE money_saving SET status = 'Claimed' WHERE id = ?";
        $stmtUpdateStatus = $con->prepare($sqlUpdateStatus);
        $stmtUpdateStatus->bind_param("i", $savingId);
        $stmtUpdateStatus->execute();

        // Add amount to user's balance
        $sqlAddToBalance = "UPDATE balance SET amount = amount + ? WHERE userid = ?";
        $stmtAddToBalance = $con->prepare($sqlAddToBalance);
        $stmtAddToBalance->bind_param("ii", $savedAmount, $userid);
        $stmtAddToBalance->execute();

        $_SESSION['message'] = "উত্তোলন সফল হয়েছে"; // Withdrawal successful
		$stmtUpdateStatus->close();
    } else {
        $_SESSION['message'] = " উত্তোলন সময় হয়নি "; // Try later
    }
	
	header("Location: index.php");
    exit();
}


?>

<?php include 'header-link.php' ?>

<main>

	<?php include 'top-bar.php' ?>
	
    <section>
        <div class="container mt-2 pb-5">
            <div class="row justify-content-center">
                <div class="col-md-6">
                    <div class="card custom-card">
                        <div class="card-body">
							
							<div class="text-center">
								<i class="profile-icon fa-duotone fa-solid fa-vault"></i>
							</div>
						
                            <h6 class="card-title text-center my-3"> মানি সেভিংস </h6>
                            
                            <div class="my-3">
                                <form class="form" action="" method="POST">
                                    <div class="mb-3">
                                        <label for="inputField" class="form-label"> টাকার পরিমাণ </label>
                                        <input type="number" min="1000" class="form-control" name="amount" id="inputField" placeholder=" টাকার পরিমাণ..." required>
                                        <center>
                                            <small> সর্বনিম্ন পরিমাণ ১০০০ টাকা ! অ্যাকাউন্টে পর্যাপ্ত পরিমাণ টাকা না থাকলে লেনদেন সম্পন্ন হবে না </small>
                                        </center>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="inputField" class="form-label"> সময়কাল সিলেক্ট করুন </label>
                                        <select name="duration" class="form-select form-control" required>
                                            <option value=""> --- সিলেক্ট করুন --- </option>
                                            <option value="1"> ১ মাস </option>
                                            <option value="6"> ৬ মাস </option>
                                            <option value="12"> ১ বছর </option>
                                        </select>
                                    </div>

                                    <div class="mb-3">
                                        <label for="pinField" class="form-label"> পিন </label>
                                        <input type="text" class="form-control" name="pin" id="pinField" placeholder=" পিন..." required>
                                    </div>

                                    <div class="d-grid">
                                        <button name="btn_deposit" type="submit" class="btn custom-button w-50 mx-auto mb-1"> কনফার্ম করুন </button>
                                    </div>
                                </form>    
                            </div>
							
							<h5 class="card-title text-center mt-5 pt-3"> <u> আপনার সেভিংস  লিস্ট  </u></h5>

                            <div class="offer-list" id="offerList">
                                <?php 
                                    $userid = $_SESSION['userid'];

									$sql = " SELECT * FROM money_saving WHERE status='Saved' AND userid = $userid ";
										
									$result = mysqli_query($con, $sql);
									$offers = [];
									if ($result) {
										while ($row = mysqli_fetch_assoc($result)) {
											$offers[] = $row;
										}
									}

                                ?>
                                
                                <?php foreach ($offers as $offer): ?>
                                    <div class="offer-card my-5 p-3">
                                        <div class="row">
                                            <div class="col">
                                                <small class="fw-bold"> টাকার পরিমাণ : <?php echo $offer['amount']; ?></small><br>
                                                <small> সময় কাল : <?php echo $offer['duration']; ?> মাস </small><br>
                                                <small> উত্তোলনের তারিখ : <?php echo $offer['ending_date']; ?></small><br>
                                            </div>
                                           
											
                                            <div class="d-grid">
												<form action="" method="POST">
                                                    <input type="hidden" name="SavingId" value="<?php echo $offer['id']; ?>">
                                                    <button name="btn_withdraw" class="btn custom-button w-100 mx-auto"> উত্তোলন <i class="fa-duotone fa-solid fa-paper-plane"></i> </button>
                                                </form>
                                            </div>
											
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</main>
</body>
</html>
