<?php
/* 
----------------------------------------------------------
  PAGE : USER GRID      
  V1.0 / 2018
  AUTHOR : SGHAIER MAHMOUD  
----------------------------------------------------------
*/


require_once(__DIR__.'/ssinclude/app-init.php');
require_once(__DIR__.'/ssinclude/app-session.php');
require_once(__DIR__.'/ssinclude/classes/class.pagination.php');

// power test security 
$power = getSessionData($sessionId, 'USER_POWER');

if ($power !== "AD" && $power !== "RH") {
    header("location:" . page_login_authoriser . "?logout=true");
    exit();
}

require_once(__DIR__.'/ssinclude/partials/header.php');


// main table/key 
$table_name="employees";
$table_key="employee_id";

// grid scripts/options 
$grid_script  = page_documents_grid;
$edit_script = page_document_edit;  
$edit_window = "false"; // if true modal mode     

//  build paging session 
$rec_by_page = 1000000 ; // no paging 
//if ($rec_by_page=="") {$rec_by_page = default_rec_by_page ;}
if (isset($_REQUEST['pg'])) $pg=$_REQUEST["pg"]; else $pg=1 ;
if (!is_numeric( $pg ) ) $pg=1;

$paging_options['url'] = $grid_script.'?pg=*VAR*';
//$paging_options['results_per_page'] = $rec_by_page;
$paging_options['results_per_page'] = $rec_by_page;
 
// get data & action if any
if (isset($_REQUEST['actionmode'])) $qry_mode=$_REQUEST['actionmode']; else $qry_mode="";
if (isset($_REQUEST['frmid'])) $qry_id=$_REQUEST["frmid"]; else $qry_id="";

$last_line = request_to_session("frmid");
if (!empty($last_line)) {
    if (!is_numeric($last_line)) {
        $last_line = decrypt_data($last_line);
    }  
}

// prepare filtering  
$session_name = request_to_session("sfrmName");

$str_comp_where = ""; // by users filter
$sql_where = " Where( 1=1 and " ; // grid filter prepare;
 

// grid sorting vars 
$order_by_list = "[$table_key,'statuses.status_type','statuses.status_type','statuses.status_type', 'statuses.status_type',     'statuses.status_type']";
$default_arrow_state = 'dw';
$default_arrow_index = 0;
if (isset($_REQUEST['frmarrowstate'])) $frm_arrow_state=$_REQUEST["frmarrowstate"]; else $frm_arrow_state=$default_arrow_state ;
if (isset($_REQUEST['frmarrowindex'])) $frm_arrow_index=$_REQUEST["frmarrowindex"]; else $frm_arrow_index=$default_arrow_index ;
if ($frm_arrow_index>=0) {
    $order_by = get_order_by ($frm_arrow_index,$frm_arrow_state,$order_by_list);
}

 
/* 
----------------------------------------------------------
  SWITCHER     
----------------------------------------------------------
*/
//  verif privilege and switch to view 
switch ($qry_mode)
{
  case "":db_grid();break;
}

/* 
----------------------------------------------------------
  DB GRID VIEW      
----------------------------------------------------------
*/
function db_grid()
{
   global $sessionData; 
   global  $table_name,$table_key,$sql_where,$order_by,$db,$pg,$paging_options,$rec_by_page,$grid_script; 
   global $last_line
   ?>
<!-- ===  BREADCRUMBS === -->  

<?php if (verif_get('err')=="sucupd") { ?>
    <notify class="notify-success">  La mise à jour a été effectuée avec succès  </notify>
 <?php } ?>

 
<?php if (verif_get('err')=="sucadd") { ?>
    <notify class="notify-success">  Le nouveau document a été ajouté avec succès </notify>
 <?php } ?>

      <div class="breadcome-area">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-lg-12 col-md-12 col-sm-12 col-12">


                            <div class="breadcome-list shadow-sm search-forms">
                            
                            <!-- first row : title -->
                            <div class="row">
                                <div class="col-lg-12 col-md-12 col-sm-12 col-12">
                                        <ul class="breadcome-menu mg-b-10">
                                                        <li><a href="#"><?php echo HOME?> </a> <span class="bread-slash">/</span>
                                                        </li>
                                                        <li><span class="bread-blod"> <?php echo LIST_DOC_TITLE?> </span>
                                                        </li>
                                    </ul>
                                </div>
                            </div>  <!-- .row --> 
                            
                            <!-- 2nd row : quick search and advanced filters   -->
                            <div class="row">
                                <div class="col-lg-12 col-md-12 col-sm-12 col-12">
                                        <div class="breadcome-heading">
                                                                
                                    <div class="row no-gutters">
                                    <div class="col-lg-6 col-md-6 col-sm-12 col-12"> 
                                        <div role="search" class="sr-input-func float-left">
                                                <input name="search-trigger" id="search-trigger" value="" type="text" placeholder="Recherche..." class="search-int form-control">  
                                                <a class="ico-sr-help"><i class="fa fa-search"></i></a>
                                            </div>
                                    </div>
                                    <!--
                                    <div class="col-lg-6 col-md-6 col-sm-2 col-2">
                                        <a class="btn ico ico-filter float-left" data-toggle="collapse" data-target="#collapse-filter-form" aria-expanded="false" aria-controls="collapse-filter-form" title=""><i class="fa fa-sliders" aria-hidden="true"></i></a>
                                    </div> -->
                                    </div> <!-- .row --> 

                                    </div>
                                </div> <!-- col -->
                            </div> <!-- .row --> 

                            </div>

                    </div>
                </div>
            </div>
        </div>
<!-- /=== BREADCRUMBS ===  --> 


<!-- === CONTENT ZONE === -->  
 
 <div class="container-fluid mg-b-15">
  <div class="row">    
   <div class="col-lg-12 col-md-12 col-sm-12 col-12">
   <div class="content-wrap">  
 
    <div class="row clearfix">
                <div class="col-lg-6 col-md-6 col-sm-6">
                <div class="grid-title">
                  <h4><?php echo LIST_DOC_TITLE?>  </h4>
               </div> 
                </div>
                <div class="col-lg-6 col-md-6 col-sm-6 col-6">
                   <!--<div class="grid-item">
                      <button type="button" class="btn btn-success" id="edit-trigger"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> <?php echo MODIFY_TITLE?>  </button>
                      <?php if ( $allow_remove ) { ?> 
                      <button type="button" class="btn btn-danger" id="delete-trigger"><i class="fa fa fa-trash-o" aria-hidden="true"></i> <?php echo REMOVE_TITLE?>  </button>  
                      <?php  } ?> 
                      <button type="button" class="btn btn-primary" id="add-trigger"><i class="fa fa-plus" aria-hidden="true"></i> <?php echo ADD_DOC_TITLE?> </button>
                    </div>--> 
                </div>
    </div>
    
   <form id="grid-form" name="grid-form" action="<?php echo $grid_script ?>" method="GET">

   <?php 
   // hidden control data 
   view_hidden('grid');
 

$sql_where=substr($sql_where,0,strlen($sql_where)-4).") ";

// build sql
$sql = "
SELECT 
    e.employee_id,
    e.first_name,
    e.last_name,
    e.id_number,
    e.last_logged_in,
    f_last.name AS last_file_name,
    f_last.file_id,
    f_last.file_path AS last_file_path,
    f_last.created_on,
    f_last.file_size,
    COUNT(ef.file_id) AS total_files
FROM $table_name  e
LEFT JOIN employee_files ef ON e.employee_id = ef.employee_id
LEFT JOIN files f_last ON f_last.file_id = (
    SELECT f2.file_id
    FROM employee_files ef2
    JOIN files f2 ON ef2.file_id = f2.file_id
    WHERE ef2.employee_id = e.employee_id
    ORDER BY f2.created_on DESC
    LIMIT 1
)
GROUP BY e.employee_id, e.first_name, e.last_name, e.last_logged_in, f_last.name, f_last.file_path
ORDER BY $order_by 
";

 
 
// pagination 
try
{
    $pagination = new pagination($pg, $sql , $paging_options);  
    //$pagination->bindValue(1, 1, PDO::PARAM_INT);  
    $pagination->execute();
}
catch(paginationException $e)
{
    echo $e;
    exit();
}

    
//  If all was successful, we can do something with our results 
if($pagination->success == true)  
{  
    // Get the results 
    $rs = $pagination->resultset->fetchAll();  
     ?>
                    <div class="grid-inner">
                        <table class="table table-hover">
                            <thead>
                             <tr>
                          <th style="width:2%"><input class="i-checks" type="checkbox" name="chkselall" id="chkselall" value="all"/> </td>
                           <th style="width:8%;">Actions</th>     
                          <th style="width:30%;">Employé</th>
                    
                                <th style="width:35%;">Dernier fichier transféré</th>
                                <th style="width:25%;">Dernier accès</th>

                               
                            </tr>
                            </thead>
                            
                             <tbody id="the-grid">
                                <?php
                                foreach ($rs as $row) {
                                    $filename = (string)($row['name'] ?? '');
                                    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
                                    $icon = "unknown.png";
                                    if (in_array($ext, ['jpg', 'jpeg'])) $icon = "jpg.png";
                                    elseif ($ext == 'png') $icon = "png.png";
                                    elseif ($ext == 'pdf') $icon = "pdf.png";
                                    elseif ($ext == 'doc') $icon = "doc.png";
                                    elseif ($ext == 'docx') $icon = "docx.png";

                                    $cid = encrypt_data($row[$table_key]);

                                    $bg = '';
                                    if (is_numeric($last_line) && $row[$table_key] == $last_line) {
                                        $bg = ' style="background-color:#e6f9ff" ';
                                    }

   
                                    ?>
                                    <tr id="<?php echo $cid; ?>" <?php echo $bg; ?>>
                                        <td >
                                            <input class="i-checks" type="checkbox" name="chksel" value="<?php echo $cid; ?>">
                                        </td>

                                        <td rel="noClickDetect">
                                            <a class="btn ico-files" data-toggle="tooltip" title="<?php echo FILES_TITLE; ?>">
                                                <i class="fa fa-folder" aria-hidden="true"></i>
                                            </a>
                                        </td>

                                        <td >
                                            <?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?><br>
                                            <span class="badge badge-secondary"><?php echo htmlspecialchars($row['id_number']); ?></span><br>
                                            <small>Nombre de fichiers : (<?php echo htmlspecialchars($row['total_files']); ?>)</small>
                                        </td>

                                        <td rel="noClickDetect">
                                       
                                                <?php if (!is_null($row['file_id'])):  
                                                       // Assuming you want to generate a file URL
                                                        $fileUrl = "dw?" . encrypt_data($row['file_id']); 
                                                    ?>

                                                    <a style="display: flex; align-items: center;" 
                                                    href="<?php echo htmlspecialchars($fileUrl); ?>" 
                                                    target="_blank">

                                                        <img class="file-icon" 
                                                            src="assets/img/files/<?php echo htmlspecialchars($icon); ?>" 
                                                            alt="icon"
                                                            style="max-width: 40px; margin-right: 10px;">

                                                        <div>
                                                            <b style="color:#555 !important">
                                                                <?php echo htmlspecialchars($row['last_file_name']); ?>
                                                            </b>

                                                            <div class="text-muted small">
                                                                <?php echo htmlspecialchars($row['created_on']); ?>
                                                                (<?php echo formatFileSize($row['file_size']); ?>)
                                                            </div>
                                                        </div>
                                                    </a>
                                                <?php endif; ?>


                                        </td>

                                        <td>
                                           <small> <?php echo ($row['last_logged_in']); ?> </small>
                                        </td>
                                    </tr>
                                <?php
                                }
                                ?>
                        </tbody>
</table>

 
</div> <!-- .asset-inner -->


<div class="row">
                <div class="col-lg-6 col-md-6 col-sm-6 col-12">
                    <div class="result-paging-block">
                    <span> <?php echo PAGING_TITLE ?> <?php echo $pagination->current_page ?>  
                    <?php echo PAGING_SEPARATOR ?>  
                     <?php echo $pagination->total_pages ?>  
                        
                   - <?php echo $pagination->total_results;  ?>   <?php echo PAGING_RECORDS ?>   </span>
                    <?php //drop_down($rec_by_page,"bypage","10;20;30;50;100","10 ".BY_PAGE.";20 ".BY_PAGE.";30 ".BY_PAGE.";50 ".BY_PAGE.";100 ".BY_PAGE,"","",false,"selectfield")?>
                    </div>
                </div>

    
                <div class="col-lg-6 col-md-6 col-sm-6 col-12">
                    <nav aria-label="grid navigation" class="paging-block">
                        <?php //echo $pagination->links_html;   ?> 
                    </nav>
                </div>
        </div>
    </div>



<?php } // end test $pagination->succes  ?>

       </form>

       </div> <!-- .content-wrap --> 
      </div> <!-- .col-lg-12 col-md-12 col-sm-12 col-12 -->  
	</div>  <!-- .row --> 
    </div> <!-- .container-fluid --> 



<!-- /=== CONTENT ZONE === -->  

<!-- === MODALS ZONE === -->  


<!-- /=== MODALS ZONE === === -->  

<?php } // end db_grid function ?>


<?php
require_once(__DIR__.'/ssinclude/partials/footer.php');

?>