<?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 drive_package_rqst.id, student.userid, student.username, student.number, 
                drive_package_rqst.offer_rqst, drive_package_rqst.mobile_no, 
                drive_package_rqst.status, all_drive_package.offer_name, all_drive_package.offer_meyad, 
                sim_entry.sim_id, sim_entry.sim_name, district.dist_id, district.dist_name, all_drive_package.drive_total 
                FROM drive_package_rqst 
                LEFT JOIN student ON drive_package_rqst.userid = student.userid
                LEFT JOIN all_drive_package ON drive_package_rqst.offer_rqst = all_drive_package.offer_id
                LEFT JOIN sim_entry ON all_drive_package.offer_sim = sim_entry.sim_id
                LEFT JOIN district ON all_drive_package.offer_area = district.dist_id  
                WHERE drive_package_rqst.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') {
   
    $amount = $_POST['amount'];
    $MobileNo = $_POST['MobileNo'];
    $status = $_POST['status'];

    // Update the status in the drive_package_rqst table
    $sqlUpdate = "UPDATE drive_package_rqst SET mobile_no = ?, status = ? WHERE id = ?";
    $stmtUpdate = $con->prepare($sqlUpdate);

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

    $stmtUpdate->bind_param("ssi", $MobileNo, $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: offer-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"> A/C Name </label>
                                                <input type="text" name="Name" class="form-control" value="<?php echo htmlspecialchars($row['username']); ?>" required>
                                                                                       
										</div>

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

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

                                        <div class="mb-3">
                                            <label class="form-label"> Offer Meyad </label>
                                                <input type="text" name="OfferMeyad" class="form-control" value="<?php echo htmlspecialchars($row['offer_meyad']); ?>" required>
                                            
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label"> Offer Sim </label>
                                                <input type="text" name="OfferSim" class="form-control" value="<?php echo htmlspecialchars($row['sim_name']); ?>" required>
                                           
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label"> Offer Area </label>
                                                <input type="text" name="OfferArea" class="form-control" value="<?php echo htmlspecialchars($row['dist_name']); ?>" required>
                                           
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label"> Total (Amount + Commission) </label>
                                                <input type="text" name="amount" class="form-control" value="<?php echo htmlspecialchars($row['drive_total']); ?>" required>
                                           
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label"> Mobile No </label>
                                                <input type="text" name="MobileNo" class="form-control" value="<?php echo htmlspecialchars($row['mobile_no']); ?>" 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>
