<?php
include 'includes/config.php';
session_start();

if (!$_SESSION['email']) {
    header('location:login.php');
}
?>
<?php
$userid = intval($_GET['id']);

$userDetails = null;
$userRightsChecks = [];

$sql_user = "SELECT id, user_name, email FROM users WHERE id = :userid";
$query_user = $conn->prepare($sql_user);
$query_user->bindParam(':userid', $userid, PDO::PARAM_INT);
$query_user->execute();
$userDetails = $query_user->fetch(PDO::FETCH_OBJ);

try {
    $sql = "SELECT user_auth FROM user_rights WHERE user_id = :userid";
    $query = $conn->prepare($sql);
    $query->bindParam(':userid', $userid, PDO::PARAM_INT);
    $query->execute();

    $userRightsChecks = $query->fetchAll(PDO::FETCH_COLUMN, 0);
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>


<?php
if (isset($_POST['submit'])) {
    $user_name = $_POST['user_name'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $options = isset($_POST['options']) ? $_POST['options'] : [];
    $user_id = $_GET['id'];

    $sql_get_old_password = "SELECT password FROM users WHERE id = :user_id";
    $query_get_old_password = $conn->prepare($sql_get_old_password);
    $query_get_old_password->bindParam(':user_id', $user_id, PDO::PARAM_INT);
    $query_get_old_password->execute();
    $user_details = $query_get_old_password->fetch(PDO::FETCH_ASSOC);

    if (empty($password)) {
        $hashed_password = $user_details['password'];
    } else {
        $options_password = ['cost' => 10];
        $hashed_password = password_hash($password, PASSWORD_BCRYPT, $options_password);
    }

    try {
        $sql_check = "SELECT id FROM users WHERE (email = :email OR user_name = :user_name) AND id != :user_id";
        $query_check = $conn->prepare($sql_check);
        $query_check->bindParam(':email', $email, PDO::PARAM_STR);
        $query_check->bindParam(':user_name', $user_name, PDO::PARAM_STR);
        $query_check->bindParam(':user_id', $user_id, PDO::PARAM_INT);
        $query_check->execute();

        if ($query_check->fetch(PDO::FETCH_ASSOC)) {
            $error_msg = "⚠️ Email or User Name already exists.";
        } else {
            $sql_update_user = "UPDATE users SET user_name = :user_name, email = :email, password = :password WHERE id = :user_id";
            $query_update_user = $conn->prepare($sql_update_user);
            $query_update_user->bindParam(':user_name', $user_name, PDO::PARAM_STR);
            $query_update_user->bindParam(':email', $email, PDO::PARAM_STR);
            $query_update_user->bindParam(':password', $hashed_password, PDO::PARAM_STR);
            $query_update_user->bindParam(':user_id', $user_id, PDO::PARAM_INT);

            $conn->beginTransaction();
            $query_update_user->execute();

            $sql_delete_rights = "DELETE FROM user_rights WHERE user_id = :user_id";
            $query_delete_rights = $conn->prepare($sql_delete_rights);
            $query_delete_rights->bindParam(':user_id', $user_id, PDO::PARAM_INT);
            $query_delete_rights->execute();

            $sql_insert_rights = "INSERT INTO user_rights (user_id, user_auth) VALUES (:user_id, :user_auth)";
            $query_insert_rights = $conn->prepare($sql_insert_rights);
            foreach ($options as $option) {
                $query_insert_rights->bindParam(':user_id', $user_id, PDO::PARAM_INT);
                $query_insert_rights->bindParam(':user_auth', $option, PDO::PARAM_INT);
                $query_insert_rights->execute();
            }

            $conn->commit();
            echo "<script>
                    alert('User and User Rights updated successfully.');
                    window.location.href = 'edit_users.php?id=" . $user_id . "';
                  </script>";
        }
    } catch (PDOException $e) {
        $conn->rollBack();
        $error_msg = "Error: " . $e->getMessage();
    }
}



?>


<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Edit User</title>
    <!-- Favicon -->
    <link rel="shortcut icon" href="images/favicon.ico" />
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <!-- Typography CSS -->
    <link rel="stylesheet" href="css/typography.css">
    <!-- Style CSS -->
    <link rel="stylesheet" href="css/style.css">
    <!-- Responsive CSS -->
    <link rel="stylesheet" href="css/responsive.css">
    <style>
        ion-icon {
            font-size: 20px;
            margin-bottom: -5px;
        }
    </style>
</head>

<body>
    <!-- loader Start -->
    <div id="loading">
        <div id="loading-center">
        </div>
    </div>
    <!-- loader END -->
    <!-- Wrapper Start -->
    <div class="wrapper">
        <!-- Sidebar  -->
        <?php
        include 'includes/sidebar.php';
        ?>
        <!-- TOP Nav Bar -->
        <?php include 'includes/header.php'; ?>
        <!-- TOP Nav Bar END -->
        <!-- Page Content  -->
        <div id="content-page" class="content-page">
            <section class="login-content">
                <div class="container">
                    <div class="row align-items-center justify-content-center height-self-center">
                        <div class="col-lg-8">
                            <div class="card auth-card">
                                <div class="card-body p-0">
                                    <div class="d-flex align-items-center auth-content">
                                        <div class="col-lg-7 align-self-center">
                                            <div class="p-3">

                                                <h2 class="mb-2">Add Users</h2>
                                                <!-- <p>Login to stay connected.</p> -->
                                                <form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'] . '?id=' . $userid); ?>" data-toggle="validator">
                                                    <div class="row">
                                                        <div class="col-lg-12">
                                                            <div class="floating-label form-group">
                                                                <label>User Name</label>
                                                                <input class="floating-input form-control" name="user_name" value="<?php echo htmlentities($userDetails->user_name); ?>" type="text" placeholder="Enter User Name" autocomplete="off">

                                                            </div>
                                                        </div>
                                                        <div class="col-lg-12">
                                                            <div class="floating-label form-group">
                                                                <label>Email</label>
                                                                <input class="floating-input form-control" auto name="email" type="email" value="<?php echo htmlentities($userDetails->email); ?>" placeholder="Enter Email" autocomplete="off">

                                                            </div>
                                                        </div>
                                                        <div class="col-lg-12">
                                                            <div class="floating-label form-group">
                                                                <label>Password</label>
                                                                <input class="floating-input form-control" name="password" type="password" placeholder="Enter New Password" autocomplete="off">
                                                                <input class="floating-input form-control" name="old_password" type="hidden" value="<?php echo htmlentities($userDetails->password); ?>" placeholder="Enter Password" autocomplete="off" readonly>

                                                            </div>
                                                        </div>
                                                        <div class="col-lg-12">
                                                            <label>Departments</label>

                                                            <!-- Contacts Department -->
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="1"
                                                                        <?php echo in_array(1, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    Contacts Department
                                                                </label>
                                                            </div>

                                                            <!-- Products Department -->
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="2"
                                                                        <?php echo in_array(2, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    List Product
                                                                </label>
                                                            </div>
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="3"
                                                                        <?php echo in_array(3, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    Add Product
                                                                </label>
                                                            </div>
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="4"
                                                                        <?php echo in_array(4, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    Print Labels
                                                                </label>
                                                            </div>
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="5"
                                                                        <?php echo in_array(5, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    Units
                                                                </label>
                                                            </div>
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="6"
                                                                        <?php echo in_array(6, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    Categories
                                                                </label>
                                                            </div>
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="7"
                                                                        <?php echo in_array(7, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    Brand
                                                                </label>
                                                            </div>

                                                            <!-- Purchase Department -->
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="8"
                                                                        <?php echo in_array(8, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    List Purchase
                                                                </label>
                                                            </div>
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="9"
                                                                        <?php echo in_array(9, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    Add Purchase
                                                                </label>
                                                            </div>

                                                            <!-- Sell Department -->
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="10"
                                                                        <?php echo in_array(10, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    All Sales
                                                                </label>
                                                            </div>
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="11"
                                                                        <?php echo in_array(11, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    Add Sales
                                                                </label>
                                                            </div>
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="12"
                                                                        <?php echo in_array(12, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    List Pos
                                                                </label>
                                                            </div>
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="13"
                                                                        <?php echo in_array(13, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    Pos
                                                                </label>
                                                            </div>

                                                            <!-- Stock Transfer Department -->
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="14"
                                                                        <?php echo in_array(14, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    List Stock Receive
                                                                </label>
                                                            </div>
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="15"
                                                                        <?php echo in_array(15, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    List Stock Transfer
                                                                </label>
                                                            </div>
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="16"
                                                                        <?php echo in_array(16, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    Add Stock Transfer
                                                                </label>
                                                            </div>

                                                            <!-- Expense Department -->
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="17"
                                                                        <?php echo in_array(17, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    List Expense
                                                                </label>
                                                            </div>
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="18"
                                                                        <?php echo in_array(18, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    Add Expense
                                                                </label>
                                                            </div>
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="19"
                                                                        <?php echo in_array(19, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    Expense Categories
                                                                </label>
                                                            </div>

                                                            <!-- Reports Department -->
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="20"
                                                                        <?php echo in_array(20, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    Reports
                                                                </label>
                                                            </div>

                                                            <!-- Accounting Department -->
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="21"
                                                                        <?php echo in_array(21, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    Accounting Department
                                                                </label>
                                                            </div>

                                                            <!-- User Management Department -->
                                                            <div>
                                                                <label>
                                                                    <input type="checkbox" name="options[]" value="22"
                                                                        <?php echo in_array(22, $userRightsChecks) ? 'checked' : ''; ?>>
                                                                    User Management
                                                                </label>
                                                            </div>
                                                        </div>




                                                    </div>
                                            </div>
                                            <button type="submit" name="submit" class="btn btn-success">Edit User</button>
                                            </form>

                                        </div>
                                    </div>
                                    <br>
                                    <!-- <div class="col-lg-5 content-right">
                                        <img src="../assets/images/login/01.png" class="img-fluid image-right" alt="">
                                    </div> -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
        </div>
        </section>
    </div>
    <!-- Wrapper END -->
    <!-- Footer -->
    <?php include 'includes/footer.php'; ?>
    <nav class="iq-float-menu">
        <input type="checkbox" href="#" class="iq-float-menu-open" name="menu-open" id="menu-open" />
        <label class="iq-float-menu-open-button" for="menu-open">
            <span class="lines line-1"></span>
            <span class="lines line-2"></span>
            <span class="lines line-3"></span>
        </label>
        <button class="iq-float-menu-item bg-info" data-toggle="tooltip" data-placement="top" title="Direction Mode"
            data-mode="rtl"><i class="ri-text-direction-r"></i></button>
        <button class="iq-float-menu-item bg-danger" data-toggle="tooltip" data-placement="top" title="Color Mode"
            id="dark-mode" data-active="true"><i class="ri-sun-line"></i></button>
        <button class="iq-float-menu-item bg-warning" data-toggle="tooltip" data-placement="top" title="Comming Soon"><i
                class="ri-palette-line"></i></button>
    </nav>
    <!-- Footer END -->
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="js/jquery.min.js"></script>
    <!-- Rtl and Darkmode -->
    <script src="js/rtl.js"></script>
    <script src="js/customizer.js"></script>
    <script src="js/popper.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <!-- Appear JavaScript -->
    <script src="js/jquery.appear.js"></script>
    <!-- Countdown JavaScript -->
    <script src="js/countdown.min.js"></script>
    <!-- Counterup JavaScript -->
    <script src="js/waypoints.min.js"></script>
    <script src="js/jquery.counterup.min.js"></script>
    <!-- Wow JavaScript -->
    <script src="js/wow.min.js"></script>
    <!-- Apexcharts JavaScript -->
    <script src="js/apexcharts.js"></script>
    <!-- Slick JavaScript -->
    <script src="js/slick.min.js"></script>
    <!-- Select2 JavaScript -->
    <script src="js/select2.min.js"></script>
    <!-- Owl Carousel JavaScript -->
    <script src="js/owl.carousel.min.js"></script>
    <!-- Magnific Popup JavaScript -->
    <script src="js/jquery.magnific-popup.min.js"></script>
    <!-- Smooth Scrollbar JavaScript -->
    <script src="js/smooth-scrollbar.js"></script>
    <!-- lottie JavaScript -->
    <script src="js/lottie.js"></script>
    <!-- Chart Custom JavaScript -->
    <script src="js/chart-custom.js"></script>
    <!-- Custom JavaScript -->
    <script src="js/custom.js"></script>
</body>

</html>