<?php 
    include("../connection.php");
    include("../user.php");
?>
<link rel="stylesheet" href="../css/sweet-alert.css" /> 

<?php
    $user = $_SESSION['user'];
    $cur_date = date("Y-m-d");

    $user_id = $_REQUEST['user'];
    $branch_id = $_REQUEST['branch_name'];
    $division_id = $_REQUEST['divison_name'];
    $role_code = $_REQUEST['role'];

    // Check if role mapping exists for the user
    $sql1 = mysqli_query($con, "SELECT * FROM role_mapping WHERE user_id='$user_id' AND status='0'");
    $row1 = mysqli_num_rows($sql1);

    if ($row1 >= 1) {
        // Update old role mapping
        $update_role = mysqli_query($con, "UPDATE role_mapping SET status='1', to_date='$cur_date', modified_by='$user', modified_on='$cur_date' WHERE user_id='$user_id'");

        // Insert new role mapping
        $insert_role = mysqli_query($con, "INSERT INTO role_mapping(code, user_id, status, from_date, created_by) VALUES ('$role_code', '$user_id', '0', '$cur_date', '$user')");
    } else {
        // Insert new role mapping
        $insert_role = mysqli_query($con, "INSERT INTO role_mapping(code, user_id, status, from_date, created_by) VALUES ('$role_code', '$user_id', '0', '$cur_date', '$user')");
    }

    // Branch mapping
    $sql2 = mysqli_query($con, "SELECT * FROM branch_mapping WHERE user_id='$user_id'");
    $row2 = mysqli_num_rows($sql2);

    if ($row2 >= 1) {
        // Update old branch mapping
        $update_branch = mysqli_query($con, "UPDATE branch_mapping SET status='1', to_date='$cur_date', modified_by='$user', modified_on='$cur_date' WHERE user_id='$user_id'");

        // Insert new branch mapping
        $insert_branch = mysqli_query($con, "INSERT INTO branch_mapping(branch_id, division_id, user_id, status, from_date, created_by, created_on) VALUES ('$branch_id', '$division_id', '$user_id', '0', '$cur_date', '$user', '$cur_date')");
    } else {
        // Insert new branch mapping
        $insert_branch = mysqli_query($con, "INSERT INTO branch_mapping(branch_id, division_id, user_id, status, from_date, created_by, created_on) VALUES ('$branch_id', '$division_id', '$user_id', '0', '$cur_date', '$user', '$cur_date')");
    }

    if ($insert_role) {	
?>
    <script>
        setTimeout(function() {
            swal({
                title: "Successfully",
                text: "Completed!",
                type: "success"
            }, function() {
                window.location = "user_master.php";
            });
        }, 100);
    </script>  
<?php
    } else {
?>
    <script>
        setTimeout(function() {
            swal({
                title: "Not",
                text: "Completed!",
                type: "error"
            }, function() {
                window.location = "user_master.php";
            });
        }, 100);
    </script> 	  
<?php
    }
?>
<script src="../js/sweet-alert.js"></script>
