<?php

include_once(CMS_ROOTPATH."relations_cls.php");

function allow_user_edit($pers_gedcom) {
    global $dbh, $person, $person2, $foundX_match, $foundY_match, $foundX_gen, $foundY_gen,$anclvl,$dsclvl,$samefamily;
    // error_log ($_SESSION['user_id_admin']);
    $group_id = $dbh->query("SELECT user_group_id FROM humo_users WHERE user_id = " . $_SESSION['user_id_admin']);
    $groupid = $group_id->fetch(PDO::FETCH_OBJ);
    // error_log ($groupid->user_group_id);
    // *** Select permissions for the group ***
	$qry = "SELECT * FROM humo_groups WHERE group_id = " . $groupid->user_group_id;
	$group_perms = $dbh->query($qry);

	@$updperms=$group_perms->fetch(PDO::FETCH_OBJ);
	
	$isAdmin=$updperms->group_admin;
	$upd_family=$updperms->group_upd_family;
	$upd_anc=$updperms->group_upd_anc;
	$upd_desc=$updperms->group_upd_desc;
	$upd_rel=$updperms->group_upd_rel;
	$upd_relofrel=$updperms->group_upd_relofrel;
    
    unset ($anclvl,$dsclvl);
    
    //if logged in user is admin, then allow user to edit any person
    //else initialize the 
    if ($isAdmin == 'j') { return true;} else $allow_user_edit=false;
    
    
    $samefamily=false;
    $person = $_SESSION['user_gedcom'];
    $person2=$pers_gedcom;

    search_bloodrel();
    
    // error_log($foundX_match .",". $foundY_match .",". $foundX_gen .",". $foundY_gen);
    //calculate ancestor level
    if (($foundY_match!=='') AND ($foundY_match == 0))  {
       $anclvl = $foundX_gen;
    //   error_log('anclvl:'.$anclvl);
      if($anclvl==1) {$samefamily=true;}
    }
    
    //calculate descendant level
    if (($foundX_match!=='') AND ($foundX_match == 0)) {
       $dsclvl = $foundY_gen;
    //   error_log('desclvl:'.$dsclvl);
       if($dsclvl==1) {$samefamily=true;}
    }
  
    //sibling check
    if (($foundX_match == '1') AND ($foundY_match == '1' ) AND ($foundX_gen == '1') AND ($foundY_gen == '1')) {
      $sibling=true;
      $samefamily=true;
      error_log('sibling');
    }
  
    if($upd_family == 'y') {
      $allow_user_edit = $samefamily?true:false;
    }
    
    //check if ancestor level is within the allowed number of levels
    if(isset($anclvl) AND ($anclvl <= $upd_anc)) {
            $allow_user_edit=true;
    }
    
    //check if descendant level is within the allowed number of levels
    if(isset($dsclvl) AND ($dsclvl <= $upd_desc)) {
            $allow_user_edit=true; 
    }
    
    if($upd_rel == 'y') {
        //check if its uncle/aunt
        if (($foundX_gen == 1 ) AND ($foundY_gen == 2 )) {
           $allow_user_edit=true; 
        }
        
        //check if its nephew / niece
        if (($foundY_gen == 1 ) AND ($foundX_gen == 2 )) {
           $allow_user_edit=true; 
        }
        
        //check if its first cousins
        if (($foundY_gen == 2 ) AND ($foundX_gen == 2 )) {
           $allow_user_edit=true; 
        }
        
    }
    
    return $allow_user_edit;
}

?>