<?php
include("header.php"); 
if(isset($_POST['add_cat'])){
    $cat_name = $_POST['cat_name'];
    $cat_desc = $_POST['cat_description'];
    
    if(isset($_FILES['upload_file']['name']) && !empty($_FILES['upload_file']['name'])){
        $rawBaseName = pathinfo($_FILES['upload_file']['name'], PATHINFO_FILENAME );
        $extension = pathinfo($_FILES['upload_file']['name'], PATHINFO_EXTENSION );
        $counter = 0;
        $fname = basename($_FILES["upload_file"]["name"]);

        $doc_root = $_SERVER['DOCUMENT_ROOT'];
        if (strpos($_SERVER['REQUEST_URI'], 'timesheet_new') !== false) {
            $doc_root = $_SERVER['DOCUMENT_ROOT']."/timesheet_new";
            
        }

        while(file_exists($doc_root."/dist/assets/images/cat/".$fname)) {
            $fname = $rawBaseName . $counter . '.' . $extension;
            $counter++;
        }
        move_uploaded_file($_FILES['upload_file']['tmp_name'], $doc_root."/dist/assets/images/cat/".$fname);
        $cat_img = $fname;
   } else {
    $cat_img = $_POST['cat_img'];
   }
    
    mysqli_query($conn, "INSERT INTO db_projects_cat(cat_name, cat_slug, cat_img, description, user_id, date_time) VALUES('".$cat_name."', '".sanitize($cat_name)."', '".$cat_img."','".$cat_desc."','".$_SESSION['loggedin_user']."', '".date('Y-m-d h:i:s')."')");
}
$edit_name = '';
$edit_desc = '';
$edit_img = '';
$edit_cat_id = '';
if(isset($_POST['action']) && $_POST['action'] == 'edit_cat'){
    $get_rec = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects_cat WHERE cat_id=".$_POST['edit_id']));
   $edit_name = $get_rec['cat_name'];
   $edit_desc = $get_rec['description'];
   
   $edit_img = $get_rec['cat_img'];
   
   $edit_cat_id = $get_rec['cat_id'];

}
if(isset($_GET['delete_id']) && !empty($_GET['delete_id'])){
    mysqli_query($conn, "DELETE FROM db_projects_cat WHERE cat_id=".$_GET['delete_id']);
    echo '<script>window.history.replaceState("", "", window.location.pathname);</script>';
}
if(isset($_POST['edit_cat'])){
    mysqli_query($conn, "UPDATE db_projects_cat SET cat_name='".$_POST['cat_name']."', description='".$_POST['cat_description']."', cat_img='".$_POST['cat_img']."' WHERE cat_id=".$_POST['edit_id']);
}

?>

 <!-- Body: Body -->       
            <div class="body d-flex py-lg-3 py-md-2">
                <div class="container-xxl">
                    <div class="row align-items-center">
                        <div class="border-0 mb-4">
                            <div class="card-header py-3 no-bg bg-transparent d-flex align-items-center px-0 justify-content-between border-bottom flex-wrap">
                                <h3 class="h4 mb-0">Project Categories</h3>
                                <div class="col-auto d-flex w-sm-100 mt-2 mt-sm-0">
                                    <?php if($curr_user_type == 'admin' || $curr_user_type == 'company'):  ?>
                                    <button type="button" class="btn btn-dark btn-set-task w-sm-100" data-bs-toggle="modal" data-bs-target="#tickadd" title="Add Category"><i class="icofont-plus-circle me-2 fs-6"></i>Add Category</button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div> <!-- Row end  -->
                    <div class="row clearfix g-3">
                    <div class="col-sm-12">
                            <div class="card mb-3">
                                <div class="card-body">
                                    <table id="myProjectTable" class="table table-hover align-middle mb-0" style="width:100%">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th class="no-sort">Category Image</th>
                                                <th><span class="table-heading">Category Name</span></th> 
                                                <th class="no-sort">Category Description</th> 
                                                <th><span class="table-heading">Creation Time</span></th>   
                                                <th class="no-sort">Actions</th>  
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            if($curr_user_type == 'admin'){
                                                 $cat_query = mysqli_query($conn, "SELECT * FROM db_projects_cat order by cat_id desc");
                                             } else if($curr_user_type == 'employee' || $curr_user_type == 'manager'){

                                                $com_id = (!empty($emp_list['company_name'])) ? $emp_list['company_name'] : 0;
                                                $cat_query = mysqli_query($conn, "SELECT * FROM db_projects_cat WHERE user_id=".$com_id." order by cat_id desc");

                                             } else {

                                                $cat_query = mysqli_query($conn, "SELECT * FROM db_projects_cat WHERE user_id=".$_SESSION['loggedin_user']." order by cat_id desc");

                                             }
                                           
                                            $i = 1;
                                            $img_arr = array(
                                                    '<div class="light-info-bg"><i class="icofont-paint"></i></div>',
                                                    '<div class="bg-lightgreen"><i class="icofont-vector-path"></i></div>',
                                                    '<div class="bg-lightyellow"><i class="icofont-ui-touch-phone"></i></div>',
                                                    '<div class="light-success-bg"><i class="icofont-tick-boxed"></i></div>',
                                                    '<div class="light-orange-bg"><i class="icofont-dashboard-web"></i></div>',
                                                    '<div class="bg-careys-pink"><i class="icofont-site-map"></i></div>',
                                                    '<div class="bg-lightblue"><i class="icofont-tasks"></i></div>'
                                                );
                                           
                                            while($single_cat =  mysqli_fetch_array($cat_query)){
                                                if(is_numeric($single_cat['cat_img'])){
                                                    $img_id = $single_cat['cat_img']-1;
                                                    $show_img = $img_arr[$img_id];
                                                } else {
                                                    $show_img = "<img src='".$site_url."/dist/assets/images/cat/".$single_cat['cat_img']."' style='width:60px;'>";
                                                }
                                               
                                        


                                                echo ' <tr>
                                                            <td>
                                                                <a class="fw-bold text-secondary">#'.$i.'</a>
                                                            </td>
                                                            <td class="img_td">
                                                                '.$show_img.'
                                                            </td>
                                                            <td>
                                                                '.$single_cat['cat_name'].' 
                                                            </td>
                                                            <td>
                                                                '.mb_strimwidth($single_cat['description'], 0, 100).'
                                                            </td>
                                                            <td>
                                                                   '.$single_cat['date_time'].'
                                                            </td>
                                
                                                            <td>';
                                                            if($curr_user_type == 'admin' || $curr_user_type == 'company'):
                                                                echo '<div class="btn-group" role="group" aria-label="Basic outlined example">
                                                                    <button type="button" class="btn btn-outline-secondary edit_cat" data-bs-toggle="modal" data-bs-target="#edittickit" data-id="'.$single_cat['cat_id'].'" title="Edit"><i class="icofont-edit text-success"></i></button>
                                                                    <button type="button" class="btn btn-outline-secondary deleterow" data-bs-toggle="modal" data-bs-target="#deletecat" data-id="'.$single_cat['cat_id'].'" title="Delete"><i class="icofont-ui-delete text-danger"></i></button>
                                                                </div>';
                                                            else :
                                                                  echo '-';
                                                            endif;
                                                            echo '</td>
                                                        </tr>'; 
                                                        $i++;
                                            }
                                            ?>
                                           
                                            
                        
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                    </div>
                    </div><!-- Row End -->
                </div>
            </div>

             <!-- Add Tickit-->
            <div class="modal fade" id="tickadd" tabindex="-1"  aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered modal-md modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title  fw-bold" id="leaveaddLabel"> Add Category</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" title="Close"></button>
                    </div>
                    <div class="modal-body">
                        
                        <div class="deadline-form">
                            <form method="post" enctype="multipart/form-data">
                                <div class="mb-3">
                                        <label for="sub" class="form-label">Category Name</label>
                                        <input type="text" class="form-control" id="sub" name="cat_name" required="">
                                </div>
                                <div class="mb-3">
                                    <label for="exampleFormControlTextarea78" class="form-label">Description (optional)</label>
                                    <textarea class="form-control" id="exampleFormControlTextarea78" name="cat_description" rows="3" placeholder="Add any extra details about the request"></textarea>
                                </div>
                                <div class="mb-3">
                                    <label for="formFileMultipleoneone" class="form-label">Category Image</label>
                                    <div class="icon_groups">
                                            <input type="radio" name="cat_img" value="1" id="img_1" checked>
                                            <label class="light-info-bg" for="img_1">
                                                <i class="icofont-paint"></i>
                                            </label> 
                                           <input type="radio" name="cat_img" value="2" id="img_2">
                                            <label class="bg-lightgreen" for="img_2">
                                                <i class="icofont-vector-path"></i>
                                            </label>
                                            <input type="radio" name="cat_img" value="3" id="img_3">
                                            <label class="bg-lightyellow" for="img_3">
                                                <i class="icofont-ui-touch-phone"></i>
                                                
                                            </label>
                                            <input type="radio" name="cat_img" value="4" id="img_4">
                                            <label class="light-success-bg" for="img_4">
                                                <i class="icofont-tick-boxed"></i>
                                                
                                            </label>
                                            <input type="radio" name="cat_img" value="5" id="img_5">
                                            <label class="light-orange-bg" for="img_5">
                                                <i class="icofont-dashboard-web"></i>
                                                
                                            </label>
                                            <input type="radio" name="cat_img" value="6" id="img_6">
                                            <label class="bg-careys-pink" for="img_6">
                                                <i class="icofont-site-map"></i>
                                                
                                            </label>
                                            <input type="radio" name="cat_img" value="7" id="img_7">
                                            <label class="bg-lightblue" for="img_7">
                                                <i class="icofont-tasks"></i>
                                                
                                            </label>
                                            <?php
                                                $cat_img_arr = array();
                                                    if($curr_user_type == 'admin'){
                                                        $q = mysqli_query($conn, "SELECT * FROM db_projects_cat WHERE cat_img NOT REGEXP '^[0-9]+$'");

                                                        $no = 9;
                                                        while($r = mysqli_fetch_array($q)){
                                                            if(in_array($r['cat_img'], $cat_img_arr)){
                                                                continue;
                                                            }
                                                           array_push($cat_img_arr, $r['cat_img']);
                                                            echo '<input type="radio" name="cat_img" value="'.$r['cat_img'].'" id="img_'.$no.'">
                                                            <label class="bg-lightblue custom_img" for="img_'.$no.'">
                                                                <img src="'.$site_url.'/dist/assets/images/cat/'.$r['cat_img'].'">
                                                            </label>';
                                                            $no++;
                                                        }
                                                    } else {
                                                        $q = mysqli_query($conn, "SELECT * FROM db_projects_cat WHERE cat_img NOT REGEXP '^[0-9]+$' and user_id=".$_SESSION['loggedin_user']);
                                                       
                                                        $no = 9;
                                                        while($r = mysqli_fetch_array($q)){
                                                            if(in_array($r['cat_img'], $cat_img_arr)){
                                                                continue;
                                                            }
                                                            echo '<input type="radio" name="cat_img" value="'.$r['cat_img'].'" id="img_'.$no.'">
                                                            <label class="bg-lightblue custom_img" for="img_'.$no.'">
                                                                <img src="'.$site_url.'/dist/assets/images/cat/'.$r['cat_img'].'">
                                                            </label>';
                                                            $no++;
                                                        }

                                                    }
                                            ?>
                                            <input type="radio" name="cat_img" value="8" id="edit_img_8" style="display:none;">
                                            <label class="bg-lightblue custom_img" for="edit_img_8" style="display:none;background: transparent !important;">
                                                <img src="#">
                                            </label>
                                            <div class="upload_custom">
                                                <label class="form-label">Add Custom Image</label>
                                                <input type="file" class="upload_file" name="upload_file" accept="image/png, image/jpeg, image/jpg">

                                            </div>

                                    </div>
                                </div>
                                <input type="submit" name="add_cat" class="add_cat" style="display:none;"> 
                            </form>
                        </div>
                        
                    </div>
                    <div class="modal-footer">
                        <!-- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Done</button> -->
                        <button type="submit" class="btn btn-primary" onclick="$('.add_cat').click();" title="Save">Save</button>
                        <button type="button" class="btn btn-primary clear-btn" title="Clear">Clear</button>

                    </div>
                </div>
                </div>
            </div>

            <!-- Edit Tickit-->
            <div class="modal fade" id="edittickit" tabindex="-1"  aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered modal-md modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title  fw-bold" id="edittickitLabel"> Edit Category </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" title="Close"></button>
                    </div>
                    <div class="modal-body">
                         <form method="post" enctype="multipart/form-data">
                                <div class="mb-3">
                                        <label for="sub" class="form-label">Category Name</label>
                                        <input type="text" class="form-control" id="sub" name="cat_name" value="<?= $edit_name; ?>" required="">
                                </div>
                                <div class="mb-3">
                                    <label for="exampleFormControlTextarea78" class="form-label">Description (optional)</label>
                                    <textarea class="form-control" id="exampleFormControlTextarea78" name="cat_description" rows="3" placeholder="Add any extra details about the request"><?= $edit_desc; ?></textarea>
                                </div>
                                <div class="mb-3">
                                    <label for="formFileMultipleoneone" class="form-label">Category Image</label>
                                    <div class="icon_groups">
                                            <input type="radio" name="cat_img" value="1" id="edit_img_1" <?php if($edit_img==1){ echo "checked"; } ?>>
                                            <label class="light-info-bg" for="edit_img_1">
                                                <i class="icofont-paint"></i>
                                            </label> 
                                           <input type="radio" name="cat_img" value="2" id="edit_img_2" <?php if($edit_img==2){ echo "checked"; } ?>>
                                            <label class="bg-lightgreen" for="edit_img_2">
                                                <i class="icofont-vector-path"></i>
                                            </label>
                                            <input type="radio" name="cat_img" value="3" id="edit_img_3" <?php if($edit_img==3){ echo "checked"; } ?>>
                                            <label class="bg-lightyellow" for="edit_img_3">
                                                <i class="icofont-ui-touch-phone"></i>
                                                
                                            </label>
                                            <input type="radio" name="cat_img" value="4" id="edit_img_4" <?php if($edit_img==4){ echo "checked"; } ?>>
                                            <label class="light-success-bg" for="edit_img_4">
                                                <i class="icofont-tick-boxed"></i>
                                                
                                            </label>
                                            <input type="radio" name="cat_img" value="5" id="edit_img_5" <?php if($edit_img==5){ echo "checked"; } ?>>
                                            <label class="light-orange-bg" for="edit_img_5">
                                                <i class="icofont-dashboard-web"></i>
                                                
                                            </label>
                                            <input type="radio" name="cat_img" value="6" id="edit_img_6" <?php if($edit_img==6){ echo "checked"; } ?>>
                                            <label class="bg-careys-pink" for="edit_img_6">
                                                <i class="icofont-site-map"></i>
                                                
                                            </label>
                                            <input type="radio" name="cat_img" value="7" id="edit_img_7" <?php if($edit_img==7){ echo "checked"; } ?>>
                                            <label class="bg-lightblue" for="edit_img_7">
                                                <i class="icofont-tasks"></i>
                                                
                                            </label>
                                            <?php
                                            $cat_img_arr = array();
                                                    if($curr_user_type == 'admin'){
                                                        $q = mysqli_query($conn, "SELECT * FROM db_projects_cat WHERE cat_img NOT REGEXP '^[0-9]+$'");
                                                        $no = 9;
                                                        while($r = mysqli_fetch_array($q)){
                                                            if(in_array($r['cat_img'], $cat_img_arr)){
                                                                continue;
                                                            }
                                                            $checked = ($edit_img == $r['cat_img']) ? "checked" : "";
                                                            echo '<input type="radio" name="cat_img" value="'.$r['cat_img'].'" id="img_'.$no.'" '.$checked.'>
                                                            <label class="bg-lightblue custom_img" for="img_'.$no.'">
                                                                <img src="'.$site_url.'/dist/assets/images/cat/'.$r['cat_img'].'">
                                                            </label>';
                                                            $no++;
                                                        }
                                                    } else {
                                                        $q = mysqli_query($conn, "SELECT * FROM db_projects_cat WHERE cat_img NOT REGEXP '^[0-9]+$' and user_id=".$_SESSION['loggedin_user']);
                                                        $no = 9;
                                                        while($r = mysqli_fetch_array($q)){
                                                            if(in_array($r['cat_img'], $cat_img_arr)){
                                                                continue;
                                                            }
                                                            $checked = ($edit_img == $r['cat_img']) ? "checked" : "";
                                                            echo '<input type="radio" name="cat_img" value="'.$r['cat_img'].'" id="img_'.$no.'" '.$checked.'>
                                                            <label class="bg-lightblue custom_img" for="img_'.$no.'" >
                                                                <img src="'.$site_url.'/dist/assets/images/cat/'.$r['cat_img'].'">
                                                            </label>';
                                                            $no++;
                                                        }

                                                    }
                                            ?>
                                            <input type="radio" name="cat_img" value="8" id="edit_img_8" <?php if($edit_img==8){ echo "checked"; } ?> style="display:none;">
                                            <label class="bg-lightblue custom_img" for="edit_img_8" style="display:none;">
                                                <img src="#">
                                            </label>
                                            <div class="upload_custom">
                                                <label class="form-label">Add Custom Image</label>
                                                <input type="file" class="upload_file" name="upload_file" accept="image/png, image/jpeg, image/jpg">

                                            </div>
                                    </div>
                                </div>
                                <input type="hidden" name="edit_id" value="<?= $edit_cat_id; ?>">
                                <input type="submit" name="edit_cat" class="edit_cat" style="display:none;"> 
                            </form>
                        
                        
                        
                    </div>
                    <div class="modal-footer">
                        <!-- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Done</button> -->
                        <button type="submit" class="btn btn-primary" onclick="$('.edit_cat').click();" title="Update">Update</button>
                        <button type="button" class="btn btn-primary clear-btn" title="Clear">Clear</button>

                    </div>
                </div>
                </div>
            </div>
             <!--- Delete Category ---->
            <div class="modal fade" id="deletecat" tabindex="-1" style="display: none;" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered modal-md modal-dialog-scrollable">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title  fw-bold" id="deleteprojectLabel"> Delete item Permanently?</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" title="Close"></button>
                    </div>
                    <div class="modal-body justify-content-center flex-column d-flex">
                        <i class="icofont-ui-delete text-danger display-2 text-center mt-2"></i>
                        <p class="mt-4 fs-5 text-center">You can only delete this item Permanently</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <a href="?delete_id=34" class="del_id"><button type="button" class="btn btn-danger color-fff">Delete</button></a>

                    </div>
                </div>
                </div>
            </div>

<style type="text/css">
.icon_groups div, .icon_groups label{
    width: 60px;
    height: 60px;
    text-align: center;
    cursor: pointer;
    display: inline-block;
    color: black;
    font-size: 30px;
}
.icon_groups i {
    vertical-align: middle;
}
.icon_groups input[type="radio"] {
    display: none;
}
.icon_groups input:checked + label {
    border: 1px solid #000;
}
.img_td div {
    width: 60px;
    height: 60px;
    font-size: 30px;
    text-align: center;
    color: black;
}
.img_td div i{
    vertical-align: middle;
}
table.dataTable thead th {
    background: transparent !important;
    white-space: nowrap;
}
 
table.dataTable thead span.sort-icon {
    display: inline-block;
    padding-left: 5px;
    width: 16px;
    height: 16px;
}
label.custom_img img {
    width: 100%;
    height: 100%;
}
 

 
table.dataTable thead .sorting::before,
table.dataTable thead .sorting_asc::before,
table.dataTable thead .sorting_desc::before,
table.dataTable thead .sorting_asc_disabled::before,
table.dataTable thead .sorting_desc_disabled::before {
    content: "";
}
 
table.dataTable thead .sorting::after,
table.dataTable thead .sorting_asc::after,
table.dataTable thead .sorting_desc::after,
table.dataTable thead .sorting_asc_disabled::after,
table.dataTable thead .sorting_desc_disabled::after {
    content: "";
}  
div.upload_custom, div.upload_custom label {
    width: 100%;
    height: auto;
    font-size: medium;
    text-align: left;
    margin-top: 10px;
}
</style>
<?php
include("footer.php");   
?>
<script type="text/javascript">
$(document).on("click", ".edit_cat", function(){
    var edit_id = jQuery(this).attr("data-id");
    $.ajax({
        type:"post",
        url:"",
        data:{action:"edit_cat",edit_id:edit_id},
        success:function(res){
            
            $('#edittickit').html(jQuery(res).find('#edittickit').html());
        }

    });
});
$(document).on("click", ".deleterow", function(){
    var del_id = jQuery(this).attr("data-id");
    jQuery("#deletecat .del_id").attr("href","?delete_id="+del_id);
});
jQuery(document).on("click", "button.clear-btn", function(){
        jQuery(this).closest(".modal-content").find("input").val('');
        jQuery(this).closest(".modal-content").find("textarea").val("");
        jQuery(this).closest(".modal-content").find("select").val('').change();
});
jQuery(document).on("change", ".upload_file", function(){
    
    var data = new FormData();
    data.append('file', $(".upload_file")[0].files[0]);
    var imgname  =  $(this).val();
    var size  =  $('.upload_file')[0].files[0].size;

    var ext =  imgname.substr( (imgname.lastIndexOf('.') +1) );
    if(ext=='jpg' || ext=='jpeg' || ext=='png' )
    {
     if(size<=1000000)
     {
        var reader = new FileReader();

        reader.onload = function (e) {
           $('.custom_img[for="edit_img_8"] img').attr('src', e.target.result);
           $('.custom_img[for="edit_img_8"]').show();
        }
       reader.readAsDataURL($('.upload_file')[0].files[0]);
        
   /* $.ajax({
      url: window.location.pathname,
      type: "POST",
      data: data,
      enctype: 'multipart/form-data',
      processData: false,  // tell jQuery not to process the data
      contentType: false   // tell jQuery not to set contentType
    }).done(function(data) {
        console.log(data);
    });*/
    } else {
        alert("file size is exceeded!");
        $(this).val('');
    }
} else{
    alert("Unsupported file type!");
    $(this).val('');
}
});
</script>