<?php 

require_once('config.php');

function f_authenticate_ad($username, $password, $site)
{
    global $conn;
    $rec_found = true;

    $LDAPUserDomain = "@umsc.net";

    $SearchFor = $username;
    $SearchField = "samaccountname";

    $LDAPHost = "umsc.net";
    $dn = "DC=UMSC,DC=NET"; //Put your Base DN here

    $LDAPUser = $username; //A valid Active Directory login
    $LDAPUserPassword = $password;

    $LDAPFieldsToFind = ["*"]; //Search Felids, Wildcard Supported for returning all values

    if (!($cnx = ldap_connect($LDAPHost))) {
        die("Could not connect to LDAP server");
    }
    ldap_set_option($cnx, LDAP_OPT_PROTOCOL_VERSION, 3); //Set the LDAP Protocol used by your AD service

    ldap_set_option($cnx, LDAP_OPT_REFERRALS, 0); //This was necessary for my AD to do anything

	if ($cnx) {
		
		try{
        $ldapbind = @ldap_bind(
            $cnx,
            $LDAPUser . $LDAPUserDomain,
            $LDAPUserPassword
        );

        if ($ldapbind) {
            //echo "success";
        } else {
        }}
		catch (Exception $e){	
		}
    }

    error_reporting(E_ALL ^ E_NOTICE); //Suppress some unnecessary messages

    $filter = "($SearchField=$SearchFor*)"; //Wildcard is * Remove it if you want an exact match
    $sr = @ldap_search($cnx, $dn, $filter, $LDAPFieldsToFind);
    $info = @ldap_get_entries($cnx, $sr);
	//echo $info["count"];
    if ($info["count"] > 0) {
        $sql =
            "	SELECT 	COUNT(*) as found 
					FROM  	cf_user (NOLOCK)
					WHERE	cf_user.empl_id ='" .$username ."'";

        // $select = $pdo->prepare($stmt);
        // $select->execute();
        // $found = $select->fetch(PDO::FETCH_ASSOC);
		
		// if( !$stmt_cf_user ) {
		 // $error_message = "Error selecting table (cf_user)";
		 // returnError($error_message);
		 // die( print_r( sqlsrv_errors(), true));
		// }
		
		$stmt_cf_user = sqlsrv_query( $conn, $sql);
		
		do {
			 while ($row = sqlsrv_fetch_array($stmt_cf_user, SQLSRV_FETCH_ASSOC)) {
				 
				$found = $row['found'];
			 }
		} while ( sqlsrv_next_result($stmt_cf_user) );
		

        if ($found > 0) {
            $new = false;
        } else {
            $new = true;
        }
		

        if ($new == true) {
            for ($x = 0; $x < $info["count"]; $x++) {

                $site_cd = $_SESSION["site_cd"];
                $accname = $info[$x]["samaccountname"][0];
                $telephone = $info[$x]["telephonenumber"][0];
                $full_name = $info[$x]["name"][0];
                $mail = $info[$x]["mail"][0];
                $department = $info[$x]["department"][0];
                $title = $info[$x]["title"][0];

                $update_ldap =
                    "INSERT INTO emp_mst ( 
									site_cd, 			emp_mst_empl_id, 			emp_mst_login_id, 				emp_mst_usr_grp, 				emp_mst_name,
									emp_mst_title, 		emp_mst_status, 			emp_mst_homephone, 				emp_mst_emg_name, 				emp_mst_emg_phone,
									emp_mst_dateofhire, emp_mst_sex, 				emp_mst_date_of_birth, 			emp_mst_marital_status, 		emp_mst_payrate, 
									emp_mst_pay_period, emp_mst_remarks, 			emp_mst_privilege_template,		emp_mst_create_by, 				emp_mst_create_date, 
									audit_user, 		audit_date,					column1)
						VALUES ( 	'".$site_cd."', 	'".$accname."', 			'".$accname."', 				'WW-U', 						'".$full_name."',
									'".$title."', 		'ACT', 						'".$telephone."', 				NULL, 							NULL, 
									NULL, 				'M', 						NULL, 							'S', 							0, 
									'".$department."',	'".$mail."', 				NULL, 							'".$accname."', 				getdate(), 
									'".$accname."', 	getdate(),					'Mobile') ";

                $select_update = $pdo->prepare($update_ldap);
                $select_update->execute();
                $row = $pdo->lastInsertId();
                //$row = $select_update->fetch(PDO::FETCH_ASSOC);

                $emp_RowID = $row;

                //echo $emp_RowID;

                $update_emp_det =
                    " INSERT INTO emp_det (
									site_cd, 					mst_RowID, 					emp_det_email_id, 			emp_det_costcenter, 			emp_det_contractor, 
									emp_det_po_buyer, 			emp_det_planner, 			emp_det_supervisor, 		emp_det_mr_approver, 			emp_det_mr_limit, 
									emp_det_wr_approver,		emp_det_wo_budget_approver, emp_det_wo_approval_limit, 	emp_det_pr_approver, 			emp_det_pr_approval_limit, 
									emp_det_pm_generator, 		emp_det_em_inactive_flag, 	emp_det_available_flag, 	emp_det_invoice_approver, 		emp_det_foreman, 
									emp_det_msetup_mobile_user, emp_det_asset_tag_flag, 	emp_det_time_card_enter, 	emp_det_time_card_void, 		emp_det_wo_gen_mr_pr, 
									emp_det_wo_sched, 			emp_det_mobile, 			emp_det_core, 				emp_det_webwork, 				audit_user, 
									audit_date, 				emp_det_checklist )
							VALUES ('".$site_cd."', 			".$emp_RowID.", 			'".$mail."', 				NULL, 							'0', 
									'0', 						'0', 						NULL, 						'0', 							'0', 
									'0', 						'0', 						'0', 						'0', 							'0', 
									'0', 						'0', 						'0', 						'0', 							'0', 
									'1', 						'0', 						'0', 						'0', 							'0', 
									'0', 						'1', 						'1', 						'1', 							'".$accname."', 
									getdate(), 					'0' )";

                $select_emp_det = $pdo->prepare($update_emp_det);
                $select_emp_det->execute();
                //$row_det = $select_update->fetch(PDO::FETCH_ASSOC);

                $update_cf_user =
                    " INSERT INTO cf_user (
								empl_id,				name,				default_site,					default_language,			sys_admin,		
								status,					work_grp,			last_login_site,				last_login,					last_pwd_changed,		
								audit_user,				audit_date,			cf_user_failed_attempt,			cf_user_locked,				cf_user_disable_auto_logout,
								column1 )
							VALUES ( 				
								'".$accname."',			'".$full_name."',	'".$site_cd."',					'DEFAULT',					'0',		
								'ACT',					NULL,				'UMSC',							NULL,						NULL,		
								'".$accname."',			getdate(),			0,								'0',						'0',
								'Y' )";

                $select_cfuser = $pdo->prepare($update_cf_user);
                $select_cfuser->execute();

                $ls_site =
                    " INSERT INTO cf_site_user (site_cd, empl_id) 
					values ('".$site_cd."', '".$accname."')";

                $select_site = $pdo->prepare($ls_site);
                $select_site->execute();

                $ls_access =
                    " INSERT cf_user_access 
									(	site_cd, 		empl_id, 			menuid, exe_flag, view_flag, new_flag, edit_flag, del_flag, print_flag)
							SELECT 		'".$site_cd."', '".$accname."', 	menuid, exe_flag, view_flag, new_flag, edit_flag, del_flag, print_flag 
							FROM cf_menu_template_access  
							WHERE template_cd = 'BLANK WEB'";

                $select_access = $pdo->prepare($ls_access);
                $select_access->execute();

                $ls_itm =
                    " INSERT usg_itm(
									site_cd, 		usg_itm_usr_grp, 	usg_itm_empl_id, 	usg_itm_location, 	usg_itm_list, 	usg_itm_change, audit_user, 	audit_date )
							SELECT 	'".$site_cd."', '', 				'".$accname."', 	loc_mst_stk_loc, 	'0', 			'0', 			'".$accname."', getdate()
							FROM loc_mst
							WHERE site_cd = '".$site_cd."' ";

                $select_itm = $pdo->prepare($ls_itm);
                $select_itm->execute();

                $ls_usg_emp =
                    " INSERT usg_emp(
								site_cd, 		usg_emp_usr_grp, 	usg_emp_emp_id, 	usg_emp_level, 	usg_emp_days, 	audit_user, 	audit_date )
						VLUES ('".$site_cd."', 	'WW-U', 			'".$accname."', 	0, 				0, 				'".$accname."', GetDate() ) ";

                $select_usg_emp = $pdo->prepare($ls_usg_emp);
                $select_usg_emp->execute();

                $ls_dsh =
                    " INSERT dsh_uac( 	site_cd, 			emp_RowID, 			dsh_RowID, 			dsh_uac_flag, 			audit_user, 	audit_date )
					SELECT 				dsh_gac.site_cd, 	".$emp_RowID.",  	dsh_gac.dsh_RowID, 	dsh_gac.dsh_gac_flag, 	'".$accname."', GetDate() 
					FROM usr_grp, dsh_gac
					WHERE usr_grp.site_cd = dsh_gac.site_cd
					AND usr_grp.RowID = dsh_gac.usg_RowID
					AND usr_grp.site_cd = '".$site_cd."'
					AND usr_grp.usr_grp_usr_grp =  'WW-U' ";

                $select_dsh = $pdo->prepare($ls_dsh);
                $select_dsh->execute();
				
				
				//echo "111111";
				$authenticate_successful = true;
            }
        } else {
			//echo "22222";
            $authenticate_successful = true;
        }
    }else{
		//echo "333333";
		$authenticate_successful = false;
	}
	
	//echo "444444";
    return $authenticate_successful;
}
?>
