<?php
ob_start();
$pageTitle = 'إعدادات المستخدمين';
include 'init.php';
$do = isset($_GET['profile']) ? $_GET['profile'] : 'Manage';
if (checkadmin($_SESSION['admin'], 1, 1) == 1 || $do == "Edit" || $do == "Update") {
// if (1 == 1 ) {
    
    if ($do == 'Manage') { // Manage Members Page

        // Select All Users Except Admin 

        $stmt = $con->prepare("SELECT * FROM users ORDER BY ID ASC");

        // Execute The Statement

        $stmt->execute();

        // Assign To Variable 

        $rows = $stmt->fetchAll();

        if (!empty($rows)) { ?>
<h1 class="input-group-text text-center">إدارة المستخدمين</h1>
<div class="container">
    <a href="profile.php?profile=Add" class="btn btn-primary">
        <i class="fa-solid fa-user-plus"></i> إضافة مستخدم جديد
    </a>
    <br>
    <br>
    <div class="table-responsive">
        <table class="main-table text-center table table-bordered">
            <tr>
                <td>#ID</td>
                <td>إسم الدخول</td>
                <td>الإسم كامل</td>
                <td>الصلاحيات</td>
                <td>تاريخ التسجيل</td>
                <td>أخر تاريخ دخول</td>
                <td>Control</td>
            </tr>
            <?php
            foreach ($rows as $row) {
                $permission = "";
                $userPermissions = getUserPermissions($row['ID']);
                // if ($row['GroupID'] == 1) {
                //     $permission = "صلاحيات كاملة";
                // } else {
                //     $permission = "إضافة بيانات فقط ";
                // }
                echo "<tr>";
                echo "<td>" . $row['ID'] . "</td>";
                echo "<td>" . $row['user_name'] . "</td>";
                echo "<td>" . $row['full_name']  . "</td>";
                echo "<td>" ;
                foreach ($userPermissions as $userPermission) {
                    if ($userPermission == 0) {
                        echo "مدير الموقع <br>";
                    }else {
                        echo getName("permissions","ID",$userPermission,"name")." - ";
                    }
                }
                echo "</td>";
                echo "<td>" . $row['dateinsert'] . "</td>";
                echo "<td>" ."</td>";
                echo "<td>
                        <a href='profile.php?profile=Edit&userid=" . $row['ID'] . "' class='btn btn-success'><i class=\"fa-solid fa-user-pen\"></i></i> </a>
                        <a href='profile.php?profile=Delete&userid=" . $row['ID'] . "' class='btn btn-danger confirm'><i class='fa-solid fa-user-xmark'></i></i> </a>";
                echo "</td>";
                echo "</tr>";
            }
            ?>
            <tr>
        </table>
    </div>
</div>
<?php } else {

            echo '<div class="container">';
            echo '<div class="nice-message">لا يوجد مستخدمين حتى الان</div>';
            echo '<a href="profile.php?do=Add" class="btn btn-primary">
                        <i class="fa-solid fa-user-plus"></i> إضافة مستخدم
                    </a>';
            echo '</div>';
        } ?>
<?php
    } elseif ($do == 'Add') { // Add Page 
        ?>
        <!-- <h1 class="input-group-text text-center">إضافة مستخدم جديد</h1>
        <div class="container"> -->
        <div class="container mt-5">
            <div class="row justify-content-center">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h2 class="text-center">إضافة مستخدم جديد</h2>
                        </div>
                        <div class="card-body">
                            <form class="form-horizontal" action="?profile=Insert" method="POST">
                                <!-- Start Username Field -->
                                <div class="form-group form-group-lg">
                                    <label class="col-sm-2 control-label">إسم الدخول</label>
                                    <div class="col-sm-10">
                                        <input type="text" name="username" class="form-control" autocomplete="off"
                                            required="required" placeholder="إدخل الإسم الذى تريد الدخول به" />
                                    </div>
                                </div>
                                <!-- End Username Field -->
                                <!-- Start Password Field -->
                                <div class="form-group form-group-lg">
                                    <label class="col-sm-2 control-label">الرقم السرى</label>
                                    <div class="showpass col-sm-10">
                                        <input type="password" name="password" class="password form-control" required="required"
                                            autocomplete="new-password" placeholder="إدخل الرقم السرى وتاكد من انه قوى" />
                                        <i class="show-pass fa-solid fa-eye fa-2x" id="hide-pass"></i>
                                    </div>
                                </div>
                                <!-- End Password Field -->
                                <!-- Start Full Name Field -->
                                <div class="form-group form-group-lg">
                                    <label class="col-sm-2 control-label">الإسم بالكامل</label>
                                    <div class="col-sm-10">
                                        <input type="text" name="full" class="form-control" required="required"
                                            placeholder="إدخل إسمك كاملا" />
                                    </div>
                                </div>
                                <!-- End Full Name Field -->
                                <div class="form-group form-group-lg">
                                    <label class="col-sm-2 control-label" for="address">العنوان</label>
                                    <div class="col-sm-10">
                                        <input type="text" name="address" id="address" class="form-control" placeholder="إدخل العنوان" />
                                    </div>
                                </div>
                                <div class="form-group form-group-lg">
                                    <label class="col-sm-2 control-label" for="phone">رقم الهاتف</label>
                                    <div class="col-sm-10">
                                        <input type="text" name="phone" id="phone" class="form-control" placeholder="إدخل رقم الهاتف" />
                                    </div>
                                </div>
                                <!-- Start Submit Field -->
                                <br>
                                <div class="form-group ">
                                    <div class="col-sm-10">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fa-solid fa-user-plus"></i> إضافة مستخدم
                                        </button>
                                        <!-- <input type="submit" value="إضافة مستخدم" class="btn btn-primary btn-lg" /> -->
                                    </div>
                                </div>
                                <!-- End Submit Field -->
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php

    } elseif ($do == 'Insert') {

        // Insert Member Page

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {

            echo "<h1 class='text-center'>إدخال مستخدم</h1>";
            echo "<div class='container'>";

            /* eslam
            011001 010111 001101 101100 011000 010110 1101
            25      23      13      44      24  22      50
            ZXNsYWy0=
            */
            // Get Variables From The Form
            $user     = $_POST['username'];
            $pass     = $_POST['password'];
            $name     = $_POST['full'];
            $address  = $_POST['address'];
            $phone    = $_POST['phone'];
            $hashPass = password_hash($pass, PASSWORD_DEFAULT);
            // Validate The Form
            $formErrors = array();
            if (strlen($user) < 4) {
                $formErrors[] = 'لا يجب أن يكون إسم الدخول أقل من  <strong>4 حروف</strong>';
            }
            if (strlen($user) > 20) {
                $formErrors[] = 'لا يجب أن يكون إسم الدخول اكبر من  <strong>20 حرف</strong>';
            }
            if (empty($user)) {
                $formErrors[] = 'لا يجب أن يكون إسم الدخول  <strong>فارغ</strong>';
            }
            if (empty($pass)) {
                $formErrors[] = 'لا يجب أن تكون كلمة السر <strong>فارغة</strong>';
            }
            if (empty($name)) {
                $formErrors[] = 'لا يجب أن يكون الإسم الكامل <strong>فارغ</strong>';
            }
            // Loop Into Errors Array And Echo It
            foreach ($formErrors as $error) {
                echo '<div class="alert alert-danger">' . $error . '</div>';
            }
            // Check If There's No Error Proceed The Update Operation
            if (empty($formErrors)) {
                // Check If User Exist in Database
                $check = checkItem("user_name", "users", $user);
                if ($check == 1) {
                    $theMsg = '<div class="alert alert-danger">هذا الإسم موجود بالفعل</div>';
                    redirectHome($theMsg, 'back');
                } else {
                    // Insert Userinfo In Database
                    $stmt = $con->prepare("INSERT INTO 
                                                users(id_companie, full_name, user_name, password, address, phone, status, dateinsert)
                                            VALUES(:id_companie, :full_name, :user_name, :password, :address, :phone, 1, now()) ");
                    $stmt->execute(array(
                        'id_companie' => 1,
                        'full_name' => $name,
                        'user_name' => $user,
                        'password' => $hashPass,
                        'address' => $address,
                        'phone' => $phone
                    ));
                    // Echo Success Message
                    $theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' تمت الإضافة</div>';
                    redirectHome($theMsg, 'back');
                }
            }
        } else {

            echo "<div class='container'>";

            $theMsg = '<div class="alert alert-danger">أسف، لا يمكنك الدخول إلى هذه الصفحة مباشرة</div>';

            redirectHome($theMsg);

            echo "</div>";
        }

        echo "</div>";
    } elseif ($do == 'Edit') {
        // Check If Get Request userid Is Numeric & Get Its Integer Value
        $userid = isset($_GET['userid']) && is_numeric($_GET['userid']) ? intval($_GET['userid']) : 0;
        if ($_SESSION['admin'] != $userid && checkadmin($_SESSION['admin'], 1, 1) != 1) {
            $userid = 0;
        }
        // Select All Data Depend On This ID
        $stmt = $con->prepare("SELECT * FROM users WHERE ID = ? LIMIT 1");
        $stmt->execute(array($userid));
        $row = $stmt->fetch();
        $count = $stmt->rowCount();
        if ($count > 0) {
            ?>
            <h1 class="text-center">تعديل بيانات <?php echo $row['user_name'] ?></h1>
            <div class="container">
                <form class="form-horizontal" action="?profile=Update" method="POST">
                    <input type="hidden" name="userid" value="<?php echo $userid ?>" />
                    <!-- Start Username Field -->
                    <div class="form-group form-group-lg">
                        <label class="col-sm-2 control-label">إسم الدخول</label>
                        <div class="col-sm-10 col-md-6">
                            <input type="text" name="username" class="form-control" value="<?php echo $row['user_name'] ?>" autocomplete="off" required="required" />
                        </div>
                    </div>
                    <!-- End Username Field -->
                    <!-- Start Password Field -->
                    <div class="form-group form-group-lg">
                        <label class="col-sm-2 control-label">الرقم السرى</label>
                        <div class="col-sm-10 col-md-6">
                            
                            <input type="password" name="newpassword" class="form-control" autocomplete="new-password" placeholder="إتركه فارغ إذا كنت لا تريد تغير كلمة السر" />
                        </div>
                    </div>
                    <!-- End Password Field -->
                    <!-- Start Full Name Field -->
                    <div class="form-group form-group-lg">
                        <label class="col-sm-2 control-label">الإسم كامل</label>
                        <div class="col-sm-10 col-md-6">
                            <input type="text" name="full" value="<?php echo $row['full_name'] ?>" class="form-control" required="required" />
                        </div>
                    </div>
                    <!-- End Full Name Field -->
                    <!-- Start Submit Field -->
                    <div class="form-group form-group-lg">
                        <div class="col-sm-offset-2 col-sm-10">
                            <input type="submit" value="حفظ التعديل" class="btn btn-primary btn-lg" />
                        </div>
                    </div>
                    <!-- End Submit Field -->
                </form>
            </div>
            <?php
            // If There's No Such ID Show Error Message
        } else {

            echo "<div class='container'>";

            $theMsg = '<div class="alert alert-danger">ليس لديك صلاحية التعديل </div>';

            redirectHome($theMsg, 'back', 2);

            echo "</div>";
        }
    } elseif ($do == 'Update') { // Update Page
        echo "<h1 class='text-center'>تحديث البيانات</h1>";
        echo "<div class='container'>";
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $formErrors = array();
            // Get Variables From The Form
            $id     = $_POST['userid'];
            $user_name     = $_POST['username'];
            $name     = $_POST['full'];
            if ($_SESSION['admin'] != $id && checkadmin($_SESSION['admin']) != 1 ) {
                $theMsg = '<div class="alert alert-danger">ليس لديك صلاحية التعديل </div>';
                redirectHome($theMsg, 'back');
            }
            $sqlname = $con->prepare("SELECT * from users where ID= ? ");
            $sqlname->execute(array($id));
            $user = $sqlname->fetch(PDO::FETCH_ASSOC);
            $oldpass = $user['password'];
            // Password Trick
            $pass = empty($_POST['newpassword']) ? $oldpass : password_hash($_POST['newpassword'],  PASSWORD_DEFAULT);
            // Validate The Form
            if (strlen($user_name) < 4) {
                $formErrors[] = 'لا يجب أن يكون إسم الدخول أقل من  <strong>4 حروف</strong>';
            }
            if (strlen($user_name) > 20) {
                $formErrors[] = 'لا يجب أن يكون إسم الدخول اكبر من  <strong>20 حرف</strong>';
            }
            if (empty($user_name)) {
                $formErrors[] = 'لا يجب أن يكون إسم الدخول  <strong>فارغ</strong>';
            }

            if (empty($name)) {
                $formErrors[] = 'لا يجب أن يكون إسم الكامل <strong>فارغ</strong>';
            }

            // Loop Into Errors Array And Echo It

            foreach ($formErrors as $error) {
                echo '<div class="alert alert-danger">' . $error . '</div>';
            }

            // Check If There's No Error Proceed The Update Operation

            if (empty($formErrors)) {

                $stmt2 = $con->prepare("SELECT * FROM users WHERE user_name = ? AND  ID != ?");

                $stmt2->execute(array($user_name, $id));

                $count = $stmt2->rowCount();

                if ($count == 1) {

                    $theMsg = '<div class="alert alert-danger">إسم المستخدم هذا (' . $user_name . ') موجود بالفعل</div>';

                    redirectHome($theMsg, 'back', 5);
                } else {
                    // Update The Database With This Info

                    $stmt = $con->prepare("UPDATE users SET user_name = ?, password = ?, full_name = ? WHERE ID = ?");

                    $stmt->execute(array($user_name, $pass, $name, $id));

                    // Echo Success Message

                    $theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' تم تحديث البيانات</div>';

                    redirectHome($theMsg, 'back', 5);
                }
            }
        } else {

            $theMsg = '<div class="alert alert-danger">أسف، لا يمكنك الدخول إلى هذه الصفحة مباشرة</div>';

            redirectHome($theMsg);
        }

        echo "</div>";
    } elseif ($do == 'Delete') { // Delete Member Page

        echo "<h1 class='text-center'>Delete Member</h1>";
        echo "<div class='container'>";

        // Check If Get Request userid Is Numeric & Get The Integer Value Of It

        $userid = isset($_GET['userid']) && is_numeric($_GET['userid']) ? intval($_GET['userid']) : 0;
        if (checkadmin($_SESSION['admin'], 1, 1) != 1) {
            $check = 0;
        } else {
            $check = checkItem('ID', 'users', $userid);
        }
        // If There's Such ID Show The Form
        if ($check > 0) {
            $stmt = $con->prepare("DELETE FROM users WHERE ID = :zuser");
            $stmt->bindParam(":zuser", $userid);
            $stmt->execute();
            $theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' تم الحذف بنجاح</div>';

            redirectHome($theMsg, 'back');
        } else {

            $theMsg = '<div class="alert alert-danger">برجاء إتباع رابط صحيح</div>';

            redirectHome($theMsg);
        }

        echo '</div>';
    } elseif ($do == "add_permissions") {
    ?>
<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h2 class="text-center"  id="err">إعطاء الصلاحيات</h2>
                </div>
                <div class="card-body">
                    <form action="<?php echo $_SERVER['PHP_SELF'] ?>?profile=insert_permissions" method="post">
                        <div class="form-group">
                            <label for="username">اسم المستخدم:</label>
                            <select class="form-control" id="username" name="username" required>
                                <?php
                                    $statement = $con->prepare("SELECT * FROM users");
                                    $statement->execute(array());
                                    $count = $statement->rowCount();
                                    if ($count > 0) {
                                        $rows = $statement->fetchAll();
                                        foreach ($rows as $row) {
                                            define ("id_user" , $row["ID"]);
                                            echo "<option value=\"{$row["ID"]}\">{$row["user_name"]}</option>";
                                        }
                                    } else {
                                        echo '<option value="">لا يوجد مستخدمين</option>';
                                    }
                                    ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="role">دور المستخدم:</label>
                            <select class="form-control" id="department" name="department" required>
                                <?php
                                    // عرض أدوار المستخدمين في قائمة منسدلة
                                    $statement = $con->prepare("SELECT * FROM departments");
                                    $statement->execute(array());
                                    $count = $statement->rowCount();
                                    if ($count > 0) {
                                        $rows = $statement->fetchAll();
                                        foreach ($rows as $row) {
                                            define ("id_departments" , $row["ID"]);
                                            echo '<option value="'.$row["ID"].'">'.$row["name"].'</option>';
                                        }
                                    } else {
                                        echo '<option value="">لا يوجد أدوار</option>';
                                    }
                                    ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>صلاحيات المستخدم:</label>

                            <?php
                                    $userPermissions = getUserPermissions(id_user,id_departments);
                                    // print_r($userPermissions);
                                    $statement = $con->prepare("SELECT * FROM permissions");
                                    $statement->execute(array());
                                    $count = $statement->rowCount();
                                    if ($count > 0) {
                                        $rows = $statement->fetchAll();
                                        foreach ($rows as $row) {
                                            $checked = in_array($row["ID"], $userPermissions) ? 'checked' : '';
                                            ?>
                                            <div class="form-check">
                                                <input type="checkbox" class="form-check-input" id="permissions" name="permissions[]"
                                                    value="<?php echo $row["ID"]; ?>" <?php echo $checked;?>>
                                                <label class="form-check-label" for="fullControl"><?php echo $row["name"]; ?></label>
                                            </div>
                                            <?php
                                        }
                                    } else {
                                        echo '<option value="">لا يوجد صلاحيات</option>';
                                    }
                                ?>
                            <!-- <div class="form-check">
                                    <input type="checkbox" class="form-check-input" id="fullControl" name="permissions[]" value="fullControl">
                                    <label class="form-check-label" for="fullControl">تحكم كامل</label>
                                </div> -->
                        </div>
                        <button type="submit" class="btn btn-primary">إعطاء الصلاحيات</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<?php
    } elseif ($do == "insert_permissions") {
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $username = $_POST["username"];
            $department = $_POST["department"];
            $permissions = isset($_POST["permissions"]) ? $_POST["permissions"] : [];
        
            $result = insertUserPermissions($username, $department, $permissions);
            echo $result;
            redirectHome($result, "back", 2);
        }
    }
}  else {
    echo '<div class="alert alert-danger">ليس لديك صلاحية الوصول</div>';
}
include $tpl . 'footer.php';