<?php 
include '../../connection.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();
}

?>


<?php include 'header-link.php' ?>
<?php include 'nav-bar.php' ?>
<?php include 'header-top-chat.php' ?>

<!-- [ Main Content ] start -->
<div class="pcoded-main-container">
    <div class="pcoded-wrapper">
        <div class="pcoded-content">
            <div class="pcoded-inner-content">
                <div class="main-body">
                    <div class="page-wrapper">
                        <!-- [ breadcrumb ] start -->
                        <div class="page-header text-center">
                            <div class="page-block">
                                <div class="row align-items-center">
                                    <div class="col-md-12">
                                        <div class="page-header-title">
                                            <h5 class="m-b-10"> Drive & Package </h5>
                                           
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- [ Main Content ] start -->
                        <div class="row justify-content-center">
                            <!-- [ form-element ] start -->
                            <div class="col-lg-6">
                                <div class="card">
                                    <div class="card-header">
                                        <h5> Request Approval</h5>
                                    </div>
                                    <div class="card-body">
									 <!-- show error message here -->
                                            <?php if ($message): ?>
                                                <div class="alert alert-info"><?php echo htmlspecialchars($message); ?></div>
                                            <?php endif; ?>
                                        <form method="POST">
										
                                            <div class="form-group">
                                                <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="form-group">
                                                <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="form-group">
                                                <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="form-group">
                                                <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="form-group">
                                                <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="form-group">
                                                <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="form-group">
                                                <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="form-group">
                                                <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="form-group">
                                                <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>
                                            <div class="card-footer">
                                                <button type="submit" class="btn btn-primary me-2">Submit</button>
                                                <a class="btn btn-light" href="index.php"> Go Back </a>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- [ Main Content ] end -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- [ Main Content ] end -->

<?php include 'footer.php' ?>
