<?php
/* 
----------------------------------------------------------
  PAGE : EMP  MASK     
  V1.0 / 2018 / 2025 
  AUTHOR : SGHAIER MAHMOUD  
----------------------------------------------------------
*/


require_once(__DIR__.'/ssinclude/app-init.php');
require_once(__DIR__.'/ssinclude/app-session.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');

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

// get data & action if any
if (isset($_REQUEST['actionmode'])) $qry_mode=$_REQUEST['actionmode']; else $qry_mode="";
if (isset($_REQUEST['frmid']) ) {
    $qry_id=$_REQUEST["frmid"]; 
    if (!empty( $qry_id)) {
        $qry_id_c = decrypt_data($qry_id);  // clear id
        if (!is_numeric( $qry_id_c ) ) exit();  
    }
} 
else  { $qry_id=""; }
if ($qry_mode=="edit") {
 if (!is_numeric($qry_id_c)) {exit();}  
}

// main table / editable fields with default values 
// main table/key 
$table_name="employees";
$table_key="employee_id";
$main_tbl_db=array
( 
     
    'employee_id'=>'',
     /*
    'file_id'=>'',
    'created_on'=>'',  // not mapped in form 
    'updated_on'=>'',  // not mapped in form 
    'active'=>1  // not mapped in form */
);
 


/* 
----------------------------------------------------------
  SWITCHER     
----------------------------------------------------------
*/

//  verif privilege and switch
switch ($qry_mode)
{
  
case "edit":mask('edit','',true);break;
case "update":update(); break;
}
/* 
----------------------------------------------------------
  DB MASK VIEW EDIT/ADD     
----------------------------------------------------------
*/
function mask($prmmode,$prmmessage,$prmstatus)
{ 
// prepare next form actions 
global $next_mode,$table_name,$table_key,$qry_id_c,$db,$edit_script,$grid_script,$main_tbl_db;
global $second_tbl_db,$second_table_name,$second_table_key,$table_fk_key ;
global $load_reason_fk; // TEMP 

if ($prmmode=='edit') $next_mode = "update";

$request_method = $_SERVER['REQUEST_METHOD'];

if ($request_method != 'POST') {
// GET Method  Populate from db    
    if ($prmmode=='edit') { 

            try
            {
                // fetch main table
                $sql="SELECT * from ".$table_name." Where ".$table_key."=".$qry_id_c.";";
                $row=$db->query($sql)->fetch(); 
                foreach ($main_tbl_db as $key => $value) {
                    $main_tbl_db[$key] = $row[$key]; 
                }
            }
            
            catch (PDOException $e)
            {
                notify_error  ( $e->getMessage());
            }

            // Associatve Values  main table
        

        }

} else {
 // POST Method Populate from post   
  foreach ($main_tbl_db as $key => $value) {
    $main_tbl_db[$key] = verif_posted($key); 
  }
}


  if (!empty($prmmessage)) {   
      if ($prmstatus) {  
        notify_success  ( $prmmessage); }
    else {
        notify_error  ( $prmmessage ); }
    }
  
?>

<!-- ===  BREADCRUMBS === -->  
<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">
                                
                            <!--  row : title -->
                                <div class="row">
                                
                                <div class="col-lg-6 col-md-6 col-sm-6 col-6">
                                    <div class="breadcome-heading">
                                            <h5 class="m-0"> <?php echo EDIT_DOC_TITLE?>   </h5> 
                                              Nom et prénom : <?php echo $row['first_name']?>  <?php echo $row['last_name']?><br>
                                               <span class="badge badge-secondary"> Matricule : <?php echo $row['id_number']?></span>

                                    </div>
                                </div> 

                                <div class="col-lg-6 col-md-6 col-sm-6 col-6" >
                                        <ul class="breadcome-menu">
                                        <li><a href="#"><?php echo HOME?> </a> <span class="bread-slash">/</span> </li>
                                        <li><span class="bread-blod"> <?php echo EDIT_DOC_TITLE?>    </span></li>
                                    </ul>
                                </div>
                            </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">  
         
           <?php 
        // hidden control data 
         view_hidden('mask')
           ?>
           <div class="row clearfix">
                <div class="col-lg-6 col-md-6 col-sm-6 col-6">
                    <nav class="mask-title">
                         
                    </nav>
                </div>
                <div class="col-lg-6 col-md-6 col-sm-6 col-6">
                    <div class="mask-item">
                            <button type="button" class="btn" id="cancel-trigger"><i class="fa fa-chevron-left" aria-hidden="true"></i> <?php echo CANCEL_TITLE?>  </button>
                            <button type="button" class="btn btn-primary" id="upload-trigger"><i class="fa fa-upload" aria-hidden="true"></i> <?php echo VALIDATE_UPLOAD?> </button>
                    </div>
                </div>
              </div> <!-- row -->
           
              
  <div class="row">
      <!-- FROM  COL 1 -->


          <div class="col-lg-4 col-md-4 col-sm-4 col-12"> 
           <h4>  Dossiers  </h4>         
          <div class="edit-folder-tree">
                         
                        <table class="table table-hover">
                           
                           
                            <tbody id="the-folder-grid">
                            <?php
                            // Configuration (adaptées à ta table)
                            $folder_table_name = "folders";
                            $folder_order_by   = "ord ASC";
                            $folder_key_field  = "folder_id";
                            
                            $sessionId = $_COOKIE['custom_session_id'];
                            global $last_folder_line;
                            $last_folder_line = getSessionData($sessionId, 'last_folder_line');

                            // Définitions / initialisations sûres
                            $last_line = null; // valeur par défaut
                            // Si tu veux récupérer $last_line depuis l'URL ou formulaire :
                            // $last_line = isset($_GET['last_line']) ? (int)$_GET['last_line'] : null;

                            // Récupère les fichiers racine si $rs non défini
                            if (!isset($rs) || !is_array($rs)) {
                                $stmtRoot = $db->prepare("SELECT * FROM {$folder_table_name} WHERE ( parent_id IS NULL OR parent_id = 0) and active=1 ORDER BY {$folder_order_by}");
                                $stmtRoot->execute();
                                $rs = $stmtRoot->fetchAll(PDO::FETCH_ASSOC);
                                if (!$rs) $rs = []; // assurer tableau
                            }

                            // --- recursive inline rendering ---
                            $render_recursive = function($rows, $level = 0) use ($db, $folder_table_name, $folder_key_field, $folder_order_by, $last_line, &$render_recursive) {
                                global $last_folder_line;
                                // protection si $rows est vide ou non itérable
                                if (empty($rows) || !is_array($rows)) {
                                    return;
                                }
       
                                foreach ($rows as $row) {
                                    // si la ligne ne contient pas la clé attendue, sauter
                                    if (!isset($row[$folder_key_field])) continue;

                                    $cid = encrypt_data($row[$folder_key_field]);
                                    $bg = '';
                                    
                                   

                                    if (is_numeric($last_folder_line) && $row[$folder_key_field] == $last_folder_line) {
                                        $bg = '  active ';
                                    }

                                    // indentation
                                    $padding = 20 + ($level * 30);
                                    ?>
                                    <tr id="<?php echo $cid ?>"  class="bg-tr-light-2 <?php echo $bg ?>">
                                        <td style="padding-left:<?php echo $padding; ?>px;">
                                        <?php
                                            if (isset($row['visibility']) && $row['visibility'] == 'public') {
                                                echo '<img class="file-icon" src="assets/img/files/folder.png">';
                                            } else {
                                                echo '<img class="file-icon" src="assets/img/files/folder-private.png">';
                                            }
                                        ?>
                                        <b><?php echo htmlspecialchars($row['name'] ?? ''); ?></b>
                                        </td>
                                    </tr>
                                    <?php
                                    // Load subfolders recursively
                                    $sqlsub = "SELECT * FROM {$folder_table_name} WHERE parent_id = ? and active=1 ORDER BY {$folder_order_by}";
                                    $stmt = $db->prepare($sqlsub);
                                    $stmt->execute([$row[$folder_key_field]]);
                                    $subrs = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                    if (!$subrs) $subrs = [];

                                    if (!empty($subrs)) {
                                        $render_recursive($subrs, $level + 1);
                                    }
                                }
                            };

                            // call recursive rendering on main level
                            $render_recursive($rs);
                            ?>
                            </tbody>


 
                </table>



           </div>
    </div> <!-- /FROM  COL 1 --> 

 <!-- FROM  COL 2 -->
      <div class="col-lg-5 col-md-5 col-sm-5 col-12"> 
 
  
                     <h4>  Documents  </h4>         
          <div class="edit-folder-tree">
 
          <table class="table table-hover">
    <tbody id="the-files-grid">
 
        <tr class="bg-tr-light-2">
            <td>
                 
            </td>
        </tr>

    </tbody>
</table>


          </div>

          
  
      </div> 
<!-- /FROM  COL 2 --> 

<!-- FROM  COL 3 -->
      <div class="col-lg-3 col-md-3 col-sm-3 col-12"> 
                     <h4>  Options   </h4>   
                     <form action="ajax/ajaxUpload.php" class="dropzone" id="fileDropzone"></form>
                
                    <div class="row">
                        <div class="col-12 pt-3"> 
                            <label><b>Envoi SMS ?</b></label>
                                <div class="icheckbox">
                                    <?php check_box('sms_confirm',"",'i-checks') ?> 
                                    <label for="sms_confirm"> <small>SMS après l'upload </small> </label>
                                </div> 
                                </div> 
                         </div> 
 
          </div>
     
<!-- /FROM  COL 3 --> 

 <!-- #region -->
                                               



   </div>  <!-- /row  --> 



                <div class="row clearfix">
                <div class="col-lg-6 col-md-6 col-sm-6 col-6">
                    <nav class="mask-title">
                    </nav>
                </div>
                <div class="col-lg-6 col-md-6 col-sm-6 col-6">
                    <div class="mask-item d-none">
                            <button type="button" class="btn" id="cancel-trigger-bottom"><i class="fa fa-chevron-left" aria-hidden="true"></i> <?php echo CANCEL_TITLE?>  </button>
                            <button type="submit" class="btn btn-primary" id="validate-trigger-bottom"><i class="fa fa-check" aria-hidden="true"></i> <?php echo VALIDATE_TITLE?> </button>
                    </div>
                </div>
              </div> <!-- row -->
                
       
			</div> <!-- .content-wrap --> 
		</div> <!-- .col-lg-12 col-md-12 col-sm-12 col-12 -->  
	</div>  <!-- .row --> 
    </div> <!-- .container-fluid --> 

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

 

<?php 
} 
 

/* 
----------------------------------------------------------
  DB UPDATE ACTIONS 
----------------------------------------------------------
*/

function update()
{ 
    global $main_tbl_db,$table_name,$table_key,$qry_id_c,$db,$edit_script,$edit_window,$grid_script,$qry_id  ;

    // re - populate - from post 
    foreach ($main_tbl_db as $key => $value) {
        $main_tbl_db[$key] = verif_posted($key); 
    }
 
  
// 3️⃣ Si un mot de passe est fourni → vérifier qu’il n’existe pas déjà ailleurs
    if (!empty(verif_posted('password'))) {
        $stmt = $db->prepare("SELECT $table_key, password FROM $table_name WHERE $table_key <> :id");
        $stmt->execute(['id' => $qry_id]);
        $passwords = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($passwords as $row) {
            if (password_verify(verif_posted('password'), $row['password'])) {
                mask('edit', "Ce mot de passe/PIN existe déjà pour un autre utilisateur. Veuillez en choisir un autre.", false);
                return;
            }
        }
        // Si unique → on hash le nouveau mot de passe
        $main_tbl_db['password'] =   password_hash (verif_posted('password'),PASSWORD_DEFAULT); 
    } else {
        // Aucun mot de passe saisi → on ne le met pas à jour
        unset($main_tbl_db['password']);
    }

    // Build / Prepare update query  
    $sql = "UPDATE $table_name SET ";
    $i = 0;   
    foreach ($main_tbl_db as $key => $value) {
        $sql = $sql . $key."=:".$key;
        $i = $i + 1;
        if (count($main_tbl_db) > $i ) {$sql=$sql.",";}
    }
    $sql = $sql. " WHERE ".$table_key."=".$qry_id_c.";";
  
   
    try
    {
        $stmt = $db->prepare($sql);
        $stmt->execute($main_tbl_db);
         
        if ($edit_window=='true') {  // check window mode 
        // close window (todo)
        } else { // redirect 
        $newURL = $grid_script."?err=sucupd&frmid=".$qry_id ;
        js_redirect( $newURL) ; 
        //mask ( 'edit', "La mise à jour a été effectuée avec succès" , true  );
        }

    }
    catch (PDOException $e)
    {
        mask ( 'edit', $e->getMessage() , false );
    }
}
 
require_once(__DIR__.'/ssinclude/partials/footer.php');
?>