<?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_employee_grid;
$edit_script = page_employee_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
(
   
    'first_name'=>'',
    'last_name'=>'',
    'phone_number'=>'',
    'email'=>'',
    'id_number'=>'',
    'password'=>'',
    'schedule_group'=>'' // NEW
   /*
    '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 "add":mask('add','',true);break;
case "update":update(); break;
case "addnew":addnew();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";
if ($prmmode=='add') $next_mode = "addnew";

$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 ($prmmode == "edit") ? EDIT_EMP_TITLE : ADD_EMP_TITLE; ?>       
                                             </h5> 
                                    </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 ($prmmode == "edit") ? EDIT_EMP_TITLE : ADD_EMP_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">  
        <form action="<?php echo $edit_script ?>" method="POST" id="mask-form" name="mask-form" class="needs-validation mask-form" novalidate> <!-- FORM WRAPPER  -->
           <?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="validate-trigger"><i class="fa fa-check" aria-hidden="true"></i> <?php echo VALIDATE_TITLE?> </button>
                    </div>
                </div>
              </div> <!-- row -->
           
              
  <div class="row">
      <!-- FROM  COL 1 -->


          <div class="col-lg-6 col-md-6 col-sm-6 col-12"> 
                    
          <div class="form-group">
                        <label for="first_name"> Nom </label>
                        <input name="first_name" id="first_name" required  type="text" class="form-control" placeholder="" value="<?php echo $main_tbl_db['first_name']?>">
                        <div class="invalid-tooltip"> Nom manquant  </div>
                        <span class="help-block small"></span>
                    </div>

                    <div class="form-group">
                        <label for="last_name"> Prénom </label>
                        <input name="last_name" id="last_name" required  type="text" class="form-control" placeholder="" value="<?php echo $main_tbl_db['last_name']?>">
                        <div class="invalid-tooltip"> Prénom manquant  </div>
                        <span class="help-block small"></span>
                    </div>

                     <div class="form-group" >
                        <label for="email2"> Matricule </label> 
                        <input name="id_number" id="id_number" required  minlength="4" maxlength="12"  type="text" class="form-control" placeholder=""   value="<?php echo $main_tbl_db['id_number']?>">
                        <div class="invalid-tooltip"> N° Matricule manquant   </div>
                        <span class="help-block small"></span>
                    </div> 

                    <div class="form-group">
                    <label for="schedule_group"> Groupe horaire </label>
                    <?php 
                        drop_down(
                            $main_tbl_db['schedule_group'],    // valeur sélectionnée
                            "schedule_group",                  // name + id
                            "A;B;C;D",                           // valeurs
                            "Groupe A;Groupe B;Groupe C;Groupe D",      // labels
                            "[ Sélectionnez un groupe ]",      // placeholder
                            " required ",                      // validations
                            false,
                            "form-control"
                        );
                    ?>
                    <div class="invalid-tooltip"> Sélectionner un groupe horaire </div>
                    <span class="help-block small"></span>
                </div>


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

 <!-- FROM  COL 2 -->
      <div class="col-lg-6 col-md-6 col-sm-6 col-12"> 
 
  
                    <div class="form-group">
                        <label for="phone_number"> Téléphone </label>
                        <input name="phone_number" id="phone_number" required  minlength="8" maxlength="8"  type="text" class="form-control" placeholder="" value="<?php echo $main_tbl_db['phone_number']?>">
                        <div class="invalid-tooltip"> Téléphone manquant  </div>
                        <span class="help-block small"></span>
                    </div>

                    <div class="form-group">
                        <label for="email"> Email </label>
                        <input name="email" id="email"  type="email" maxlength="60"  class="form-control" placeholder="" value="<?php echo $main_tbl_db['email']?>">
                        <div class="invalid-tooltip"> Email manquant ou invalide  </div>
                        <span class="help-block small"></span>
                    </div>

                    <div class="form-group">
                        <label for="email"> PIN Pass   </label>
                        <input  name="password" id="password"  type="text" inputmode="numeric"
                        pattern="\d{8}" minlength="8" maxlength="8" <?php echo ($prmmode == 'edit') ? '' : 'required'; ?>  class="form-control"  
                        title="Entrez exactement 8 chiffres (0-9)" value=""
                         />
                        <div class="invalid-tooltip"> PIN Pass manquant   </div>
                        <span class="help-block small"> Entrez exactement 8 chiffres (0-9)  </span>
                    </div>
 
  
      </div> <!-- /FROM  COL 2 --> 
   </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">
                            <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 -->


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

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

 

<?php 
} 
/* 
----------------------------------------------------------
  DB ADDNEW ACTIONS  
----------------------------------------------------------
*/
function addnew()
{ 
    global $main_tbl_db, $table_name, $table_key, $qry_id_c, $db, $edit_script, $edit_window, $grid_script;

    // Re-populate from POST
    foreach ($main_tbl_db as $key => $value) {
        $main_tbl_db[$key] = verif_posted($key);
    }

    /* CHECK EMAIL DUPLICATION */
    // $postedEmail = trim(verif_posted('email'));
    
    /*
    if (!empty($postedEmail)) {
        $stmt = $db->prepare("SELECT COUNT(*) FROM $table_name WHERE email = ?");
        $stmt->execute([$postedEmail]);
        $emailExists = $stmt->fetchColumn();

        if ($emailExists > 0) {
            mask('add', "Cette adresse email existe déjà. Veuillez en choisir une autre.", false);
            return;
        }
    }*/

    /* CHECK PIN REQUIRED + UNIQUE */
    $postedPin = trim(verif_posted('password'));

    if (empty($postedPin)) {
        mask('add', "Le PIN est obligatoire.", false);
        return;
    }

    // Get all encrypted pins
    $stmt = $db->prepare("SELECT password FROM $table_name w");
    $stmt->execute();
    $pins = $stmt->fetchAll(PDO::FETCH_COLUMN);

    foreach ($pins as $stored) {
        if (!empty($stored) && decrypt_pin($stored) == $postedPin) {
            mask('add', "Ce PIN existe déjà. Veuillez en choisir un autre.", false);
            return;
        }
    }

    // Encrypt new PIN
    $main_tbl_db['password'] = encrypt_pin($postedPin);

    /*  BUILD AND EXECUTE INSERT QUERY */
    $columns = implode(", ", array_keys($main_tbl_db));
    $params = ":" . implode(", :", array_keys($main_tbl_db));

    $sql = "INSERT INTO $table_name ($columns) VALUES ($params)";

    try {
        $stmt = $db->prepare($sql);
        $stmt->execute($main_tbl_db);

        if ($stmt->rowCount() > 0) {
            if ($edit_window == 'true') {
                // TODO
            } else {
                $newURL = $grid_script . "?err=sucadd&frmid=" . encrypt_data($db->lastInsertId());
                js_redirect($newURL);
            }
        } else {
            mask('edit', "L’ajout a échoué.", false);
        }

    } catch (PDOException $e) {
        mask('edit', $e->getMessage(), false);
    }
}



/*  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;

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

    $postedPin = trim(verif_posted('password'));

    // Si un PIN est fourni → vérifier unicité
    if (!empty($postedPin)) {

        // Vérifier que le PIN n'existe pas chez un autre utilisateur
        $stmt = $db->prepare("SELECT password 
                            FROM $table_name 
                            WHERE $table_key <> :id");
        $stmt->execute(['id' => $qry_id_c ]);
        $rows = $stmt->fetchAll(PDO::FETCH_COLUMN);

        foreach ($rows as $storedPin) {
            if (!empty($storedPin) && decrypt_pin($storedPin) === $postedPin) {
                mask('edit', "Ce PIN existe déjà pour un autre utilisateur. Veuillez en choisir un autre.", false);
                return;
            }
        }

        // PIN unique → on crypte
        $main_tbl_db['password'] = encrypt_pin($postedPin);

    } else {

        // Aucun PIN fourni → ne pas modifier le PIN existant
        unset($main_tbl_db['password']);
    }

    // Build update query  
    $sql = "UPDATE $table_name SET ";
    $i = 0;   
    foreach ($main_tbl_db as $key => $value) {
        $sql .= $key."=:".$key;
        $i++;
        if (count($main_tbl_db) > $i) { $sql .= ","; }
    }
    $sql .= " WHERE ".$table_key."=".$qry_id_c.";";

    try {
        $stmt = $db->prepare($sql);
        $stmt->execute($main_tbl_db);

        if ($edit_window=='true') {
            // TODO
        } else {
            $newURL = $grid_script."?err=sucupd&frmid=".$qry_id;
            js_redirect($newURL);
        }

    } catch (PDOException $e) {
        mask('edit', $e->getMessage(), false);
    }
}


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