<?php include 'header-link.php' ?>
<?php 
  
$message = ''; // Initialize a message variable

// Check if ID is provided in the URL
if (!isset($_GET['id'])) {
    header("Location: index.php"); // Redirect if no ID is provided
    exit();
}

$id = $_GET['id'];

$sqlRetrieve = "SELECT * FROM bill_pay WHERE id = ?";
$stmtRetrieve = $con->prepare($sqlRetrieve);

if ($stmtRetrieve === false) {
    die('Prepare failed: ' . htmlspecialchars($con->error));
}

$stmtRetrieve->bind_param("i", $id);
$stmtRetrieve->execute();
$result = $stmtRetrieve->get_result();
$row = $result->fetch_assoc();

$stmtRetrieve->close();

// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Retrieve form data
    $account_no = $_POST['account_no']; 
    $bill_org = $_POST['bill_org'];
    $bill_date = $_POST['bill_date'];
    $holder_name = $_POST['holder_name'];
    $holder_mobile = $_POST['holder_mobile'];
    $amount = $_POST['amount'];
    $area = $_POST['area'];
    $status = $_POST['status'];

    // Update the status in the bill_pay table
    $sqlUpdate = "UPDATE bill_pay SET account_no = ?, bill_org = ?, bill_date = ?, holder_name = ?, holder_mobile = ?, amount = ?, area = ?, status = ? WHERE id = ?";
    $stmtUpdate = $con->prepare($sqlUpdate);

    if ($stmtUpdate === false) {
        die('Prepare failed: ' . htmlspecialchars($con->error));
    }

    $stmtUpdate->bind_param("ssssssssi", $account_no, $bill_org, $bill_date, $holder_name, $holder_mobile, $amount, $area, $status, $id);

    if ($stmtUpdate->execute()) {
        if ($stmtUpdate->affected_rows > 0) { // Check if any rows were updated
            // If status is accepted, deduct the amount from user's balance
            if ($status === 'Accepted') {
                $userid = $row['userid'];

                $sqlDeductBalance = "UPDATE balance SET amount = amount - ? WHERE userid = ?";
                $stmtDeductBalance = $con->prepare($sqlDeductBalance);

                if ($stmtDeductBalance === false) {
                    die('Prepare failed: ' . htmlspecialchars($con->error));
                }

                $stmtDeductBalance->bind_param("di", $amount, $userid);

                if (!$stmtDeductBalance->execute()) {
                    $message = "Failed to update balance.";
                }

                $stmtDeductBalance->close();

                // Insert notification for accepted status
                $messageContent = ' এডমিন  আপনার  বিল পেমেন্ট  রিকোয়েস্টটি   গ্রহণ ও সম্পন্ন করেছেন ';
                $notificationStatus = 'Unread';
                $date = date('Y-m-d'); // Get current date and time

                $sqlInsertNotification = "INSERT INTO notification (userid, message, status, date) VALUES (?, ?, ?, ?)";
                $stmtInsertNotification = $con->prepare($sqlInsertNotification);

                if ($stmtInsertNotification === false) {
                    die('Prepare failed: ' . htmlspecialchars($con->error));
                }

                $stmtInsertNotification->bind_param("isss", $userid, $messageContent, $notificationStatus, $date);
                $stmtInsertNotification->execute();
                $stmtInsertNotification->close();
            } elseif ($status === 'Rejected') {
                // Insert notification for rejected status
                $userid = $row['userid'];
                $messageContent = ' এডমিন  আপনার  বিল পেমেন্ট রিকোয়েস্টটি   বাতিল করেছেন ';
                $notificationStatus = 'Unread';
                $date = date('Y-m-d'); // Get current date and time

                $sqlInsertNotification = "INSERT INTO notification (userid, message, status, date) VALUES (?, ?, ?, ?)";
                $stmtInsertNotification = $con->prepare($sqlInsertNotification);

                if ($stmtInsertNotification === false) {
                    die('Prepare failed: ' . htmlspecialchars($con->error));
                }

                $stmtInsertNotification->bind_param("isss", $userid, $messageContent, $notificationStatus, $date);
                $stmtInsertNotification->execute();
                $stmtInsertNotification->close();
            }

            header("Location: bill-pay-rqst.php");
            $message = "Update successful.";
        } else {
            $message = "No changes made.";
        }
    } else {
        $message = "Error updating record: " . htmlspecialchars($stmtUpdate->error);
    }

    $stmtUpdate->close();
}
?>


    <main>
	
        <section>   
			<div class="container mb-5">
				<div class="row justify-content-center">
					<div class="col-md-6">
						<div class="card custom-card">
							<div class="card-body">
								<h6 class="card-title text-center d-block"> Update Request </h6>
                                       
                                           
								
									<form class="form" action="" method="POST">

                                        <div class="mb-3">
                                            <label class="form-label"> SMS/Account Info </label>
                                                <input type="text" name="account_no" class="form-control" value="<?php echo htmlspecialchars($row['account_no']); ?>" required>
                                         
                                            
										</div>

                                        <div class="mb-3">
                                            <label class="form-label"> Bill Organization </label>
                                                <input type="text" name="bill_org" class="form-control" value="<?php echo htmlspecialchars($row['bill_org']); ?>" required>
                                           
                                           
										</div>

                                        <div class="mb-3">
                                            <label class="form-label"> Bill Date </label>
                                                <input type="date" name="bill_date" class="form-control" value="<?php echo htmlspecialchars($row['bill_date']); ?>" required>
                                          
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label"> Holder Name </label>
                                                <input type="text" name="holder_name" class="form-control" value="<?php echo htmlspecialchars($row['holder_name']); ?>" required>
                                           
                                        </div>
                                      
                                        <div class="mb-3">
                                            <label class="form-label"> Mobile No </label>
                                                <input type="text" name="holder_mobile" class="form-control" value="<?php echo htmlspecialchars($row['holder_mobile']); ?>" required>
                                         
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label"> Amount </label>
                                                <input type="text" name="amount" class="form-control" value="<?php echo htmlspecialchars($row['amount']); ?>" required>
                                            
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label"> Area </label>
                                                <input type="text" name="area" class="form-control" value="<?php echo htmlspecialchars($row['area']); ?>" required>
                                        </div>

										<div class="mb-3">
                                            <label class="form-label"> Choose Status </label>
                                                <select name="status" class="form-select form-control" required>
                                                    <option value="Pending" <?php echo $row['status'] === 'Pending' ? 'selected' : ''; ?>>Pending</option>
                                                    <option value="Accepted" <?php echo $row['status'] === 'Accepted' ? 'selected' : ''; ?>>Accepted</option>
													<option value="Rejected" <?php echo $row['status'] === 'Rejected' ? 'selected' : ''; ?>>Rejected</option>
                                                </select>
										</div>

										<button type="submit" class="btn custom-button"> Save  </button>
									</form>
									
							</div>
						</div>
					</div>
				</div>
			</div>
		</section>
		

		
    </main>

    
</body>
</html>
