<?php
/*********************************************************
 * Function Name : validateLDAP
 * Author        : Your Name
 * Date          : 21-02-2026
 * Description   : 
 *    Validates user credentials against LDAP server.
 *
 * Parameters    :
 *    $username  - LDAP username
 *    $password  - LDAP password
 *
 * Returns       :
 *    TRUE  - If authentication successful
 *    FALSE - If authentication failed
 *********************************************************/
// error_reporting(E_ALL);
// ini_set('display_errors', 1);

define("LDAP_SERVER", "192.168.1.2");
define("LDAP_PORT", 389);
// define ("QN","ou=bind,dc=helb,dc=crm4,dc=dynamics,dc=com");

function validateLDAP($username, $password){
    if (empty($username) || empty($password)) {
        // ldapDebug("Username or Password is empty");
        return false;
    }
    $ldapconn = ldap_connect(LDAP_SERVER, LDAP_PORT);
    if (!$ldapconn) {
        return false;
    }
    ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);
    ldap_set_option($ldapconn, LDAP_OPT_NETWORK_TIMEOUT, 10);
    // Force proper AD login format
    if (strpos($adminUser, "@") === false) {
        $adminUser = $adminUser . "@helb.crm4.dynamics.com";
    }
    $bind = ldap_bind($ldapconn, $adminUser, $adminPass);

    if (!$bind) {
        return false;
    }
    /*
    -------------------------------------------------
    IMPORTANT: Root search (auto-detect base DN)
    -------------------------------------------------
    */
    $root = ldap_read($ldapconn, NULL, "(objectClass=*)", ["defaultNamingContext"]);
    $rootData = ldap_get_entries($ldapconn, $root);
    if ($rootData["count"] > 0) {
        $base_dn = $rootData[0]["defaultnamingcontext"][0];
    } else {
        return false;
    }
    /*
    -------------------------------------------------
    Search Filter (Active Directory Correct Way)
    -------------------------------------------------
    */
    $filter = "(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";

    // If search text provided
    if (!empty($searchText)) {
        $searchText = ldap_escape($searchText, "", LDAP_ESCAPE_FILTER);
        $filter = "(&(objectCategory=person)(objectClass=user)
                    (|(displayName=*$searchText*)
                      (mail=*$searchText*)
                      (sAMAccountName=*$searchText*))
                    (!(userAccountControl:1.2.840.113556.1.4.803:=2))
                   )";
    }

    $attributes = ["displayName", "mail", "sAMAccountName"];
    $search = ldap_search($ldapconn, $base_dn, $filter, $attributes);

    if (!$search) {
        return false;
    }
    ldap_unbind($ldapconn);
    return true;
}
function getLDAPUsers($adminUser, $adminPass, $searchText = ''){

    ldapDebug("========== START LDAP USER FETCH ==========");

    $ldapconn = ldap_connect(LDAP_SERVER, LDAP_PORT);

    if (!$ldapconn) {
        ldapDebug("❌ LDAP connection FAILED");
        return false;
    }

    ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);
    ldap_set_option($ldapconn, LDAP_OPT_NETWORK_TIMEOUT, 10);

    // Force proper AD login format
    if (strpos($adminUser, "@") === false) {
        $adminUser = $adminUser . "@helb.crm4.dynamics.com";
    }

    ldapDebug("Trying bind with: " . $adminUser);

    $bind = ldap_bind($ldapconn, $adminUser, $adminPass);

    if (!$bind) {
        ldapDebug("❌ Admin bind FAILED");
        ldapDebug("LDAP Error: " . ldap_error($ldapconn));
        return false;
    }

    ldapDebug("✅ Admin bind SUCCESS");

    /*
    -------------------------------------------------
    IMPORTANT: Root search (auto-detect base DN)
    -------------------------------------------------
    */
    $root = ldap_read($ldapconn, NULL, "(objectClass=*)", ["defaultNamingContext"]);
    $rootData = ldap_get_entries($ldapconn, $root);

    if ($rootData["count"] > 0) {
        $base_dn = $rootData[0]["defaultnamingcontext"][0];
        ldapDebug("Detected Base DN: " . $base_dn);
    } else {
        ldapDebug("❌ Could not detect Base DN");
        return false;
    }

    /*
    -------------------------------------------------
    Search Filter (Active Directory Correct Way)
    -------------------------------------------------
    */
    $filter = "(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))";

    // If search text provided
    if (!empty($searchText)) {
        $searchText = ldap_escape($searchText, "", LDAP_ESCAPE_FILTER);
        $filter = "(&(objectCategory=person)(objectClass=user)
                    (|(displayName=*$searchText*)
                      (mail=*$searchText*)
                      (sAMAccountName=*$searchText*))
                    (!(userAccountControl:1.2.840.113556.1.4.803:=2))
                   )";
    }

    $attributes = ["displayName", "mail", "sAMAccountName"];

    ldapDebug("Running LDAP search...");
    ldapDebug("Filter Used: " . $filter);

    $search = ldap_search($ldapconn, $base_dn, $filter, $attributes);

    if (!$search) {
        ldapDebug("❌ Search FAILED");
        ldapDebug("LDAP Error: " . ldap_error($ldapconn));
        return false;
    }

    $entries = ldap_get_entries($ldapconn, $search);

    ldapDebug("✅ Total Users Found: " . $entries["count"]);

    ldap_unbind($ldapconn);

    return $entries;
}
function ldapDebug($message) {
    echo "<pre style='color:blue;'>[LDAP DEBUG] " . $message . "</pre>";
}