<?php
ob_start();
session_start();
include "../config/web_mysqlconnect.php"; // database file include

function login_json_response(array $payload): void
{
    while (ob_get_level() > 0) {
        ob_end_clean();
    }
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($payload);
    exit;
}

if ($_POST['action'] === 'Login_Flow' || $_GET['action'] == 'Login_Flow') {
   include(__DIR__ . "/ldap_login.php");

    $username = $_REQUEST['loginID'];
    // $password = $_REQUEST['password'];
    $password   = $_REQUEST['output'];
    $db='ensembler';
    $company_id = '2224';

   $telephony = '1';
   $value     = $_REQUEST['value'] ?? 0;
   $loginID   = $_REQUEST['loginID'] ?? '';
   $db='ensembler';

   // ===============================
    // STEP 1: CHECK USER EXISTS
    // ===============================
    $checkUserQuery = "SELECT I_UserID, V_EmailID, I_UserStatus,
                              I_CompanyID, I_FirstLogin
                       FROM $db.tbl_mst_user_company
                       WHERE V_EmailID='$username'
                       AND I_UserStatus='1'";
// echo $checkUserQuery;
    $userResult = mysqli_query($link, $checkUserQuery);

    if (mysqli_num_rows($userResult) != 1) {

        add_audit_log(0, 'login_failed', 'null',
            'User not registered in CRM system: '.$username, $db);

        login_json_response([
            'status'=>false,
            'message'=>'User not registered in CRM system'
        ]);
    }

    $row = mysqli_fetch_assoc($userResult);
    $userid = $row['I_UserID'];

    // ===============================
    // STEP 2: CHECK LICENCE FLAG
    // ===============================

    if(!empty($value) && $value == '1'){ 
          $licenceFlag = '0'; // ldap code already check in allnc_new.php so ignore ldap validation code [Aarti][26-03-2026]
    }else{
          $licenceFlag = '0';
    }
  
    $loginSuccess = false;

    // ===============================
    // IF LICENCE ACTIVE → LDAP REQUIRED
    // ===============================
    if ($licenceFlag == '1') {
        $ldapPassword = $_POST['passID'];   // plain
        $dbPassword   = $_POST['output'];   // hashed

        $ldapValid = validateLDAP($username, $ldapPassword);

        if ($ldapValid) {

            // ================= LDAP SUCCESS =================

            $query = "SELECT V_Password
                      FROM $db.tbl_mst_user_company
                      WHERE V_EmailID='$username'";

            $result = mysqli_query($link,$query);
            $user = mysqli_fetch_assoc($result);

            if($user){

                $dbStoredPassword = $user['V_Password'];

                // Update DB password if different
                if($dbStoredPassword != $dbPassword){

                    $update = "UPDATE $db.tbl_mst_user_company
                               SET V_Password='$dbPassword',
                                   password_change_date=NOW()
                               WHERE I_UserID='$userid'";

                    mysqli_query($link,$update);
                    // Update asterisk password 
                    $sql15="UPDATE  $db_asterisk.`autodial_users` SET `pass` = '$ldapPassword'  WHERE emailid = '$username'";
                     mysqli_query($link,$sql15) or die ("invalid query autodial_users:" . mysqli_error($link));

                    add_audit_log($userid,'password_update','null',
                        'Password synced from LDAP',$db);
                }
            }

            $_SESSION['login_source'] = 'ldap';
            $loginSuccess = true;

        }
        else {

            // ================= LDAP FAIL → CHECK DB =================

            $localQuery = "SELECT I_UserID
                           FROM $db.tbl_mst_user_company
                           WHERE V_EmailID='$username'
                           AND V_Password='$dbPassword'
                           AND I_UserStatus='1'";

            $localRes = mysqli_query($link,$localQuery);

            if(mysqli_num_rows($localRes)==1){

                $_SESSION['login_source'] = 'local';
                $loginSuccess = true;

                add_audit_log($userid,'login','null',
                    'Login success via LOCAL DB',$db);

            } else {

                add_audit_log($userid,'login_failed','null',
                    'LDAP fail + DB password mismatch',$db);

                login_json_response([
                    'status'=>false,
                    'message'=>'Invalid email or password'
                ]);
            }
        }
    }

    // ===============================
    // IF LICENCE NOT ACTIVE → NORMAL DB LOGIN
    // ===============================
    else {

        $localQuery = "SELECT I_UserID
                       FROM $db.tbl_mst_user_company
                       WHERE V_EmailID='$username'
                       AND V_Password='$password'
                       AND I_UserStatus='1'";

        $localRes = mysqli_query($link, $localQuery);

        if (mysqli_num_rows($localRes) != 1) {

            add_audit_log($userid, 'login_failed', 'null',
                'Wrong local password: '.$username, $db);

            login_json_response([
                'status'=>false,
                'message'=>'Invalid email or password'
            ]);
        }

        $loginSuccess = true;
        $_SESSION['login_source'] = 'local';
        
        // TEMP SESSION (NO DASHBOARD YET)
        $_SESSION['TEMP_LOGIN'] = true;
        $_SESSION['TEMP_USERID'] = $row['I_UserID'];
        $_SESSION['TEMP_EMAIL']  = $row['V_EmailID'];
        $_SESSION['TEMP_COMPANY'] = $row['I_CompanyID'];

        $userid = $row['I_UserID'];

        $sql_group="select atxGid from $db.unigroupdetails where ugdContactID='$userid'";
        $res_group=mysqli_query($link,$sql_group);
        $row_group=mysqli_fetch_array($res_group);
        $user_group=$row_group['atxGid'];
        $_SESSION['user_group']    =$user_group;


        add_audit_log($userid, 'login', 'null',
            'Login success via LOCAL DB', $db);
    }
    // ===============================
    // COMMON SESSION SET
    // ===============================
    if ($loginSuccess) {

      $userstatus  = $row['I_UserStatus'];
      $first_login = $row['I_FirstLogin'];
      $company_id  = $row['I_CompanyID'];
      $email       = $row['V_EmailID'];

         // ---------------- PASSWORD EXPIRE ----------------
        if (isPasswordExpired($userid) === '3') {
            login_json_response([
                'status'   => false,
                'message'  => 'Password expired',
                'redirect' => "web_changepass.php?userid=$userid&comp=$company_id"
            ]);
        }

        // ---------------- RIGHTS CHECK ----------------
        if ($userid !== 1 && $telephony != 1) {
            if ($profile['i_classify'] == 0) {
                login_json_response([
                    'status' => false,
                    'message'=> "No Omnichannel rights"
                ]);
            }
        }

        // ---------------- USER STATUS ----------------
        if ($userstatus != '1') {
            login_json_response(['status'=>false,'message'=>'Account deactivated']);
        }
         // ---------------- FIRST LOGIN ----------------
        if ($first_login == '0') {
            // header("redirect: ../web_changepass.php?userid=$userid&comp=$company_id");
            // exit;
        }

        // TEMP SESSION (NO DASHBOARD YET)
        $_SESSION['TEMP_LOGIN'] = true;
        $_SESSION['TEMP_USERID'] = $row['I_UserID'];
        $_SESSION['TEMP_EMAIL']  = $row['V_EmailID'];
        $_SESSION['TEMP_COMPANY'] = $row['I_CompanyID'];

        if($_GET['value']  == '1'){
            $sid = $SNo;
            $web_admin_dashboard = base64_encode('web_admin_dashboard'); //for encode url
             $location = "CRM/dashboard_index.php?token=$web_admin_dashboard";
             ?>
          <script>
              localStorage.setItem('__AGENT_LOGIN_ID', '<?= $sid ?>');
                  window.location.href = '../<?= $location ?>';
          </script>
            <?php 
        }else{
            login_json_response([
                'status' => true,
                'redirect' => 'dashboard_login.php?type=campaign'
            ]);
        }

    }
}


// function for login 
    function add_audit_log($user_id, $actionlog, $ticketid, $comments, $db, $types=''){
       global $link,$db;
       $created_on=date("Y-m-d H:i:s");
       $ip = getenv('REMOTE_ADDR');
        $sql_ins1="INSERT INTO $db.web_audit_history(user_id, action, created_on, ticket_id, comments, ip_address, case_process_type)
       VALUES('$user_id', '$actionlog', NOW(), '$ticketid', '$comments' , '$ip', '$types')";
       mysqli_query($link,$sql_ins1)or die(mysqli_error($link).'Err web_audit_history');
   }

   function telephony_flag($user,$flag){
     global $link,$db;
      $query = $link->query("UPDATE tbl_mst_user_company SET telephony_flag = '$flag' WHERE V_EmailID = '$user'");
      if($query){
         return true;
      }
   }


   function classify($userid){
      global $link,$db;
      $query = $link->query("SELECT i_classify FROM uniuserprofile WHERE AtxUserID = '$userid' AND AtxUserStatus = 1 ");
      $fetch = $query->fetch_assoc();
      $i_classify = $fetch['i_classify'];
      return $i_classify;
   }

   //Function to check if the password is expired (more than 3 months old) - aarti
   function isPasswordExpired($user_id) {  
      global $db ,$link;
      $response = '';
      $sql_name="select password_change_date from $db.tbl_mst_user_company where I_UserID='$user_id'";
      $res_name=mysqli_query($link,$sql_name);
      $num_user_login=mysqli_num_rows($res_name);
      $response = '';
      if($num_user_login>0){
         $row_name=mysqli_fetch_array($res_name);
             
         if($row_name['password_change_date'] != '0000-00-00 00:00:00'){
            $password_change_date = strtotime($row_name['password_change_date']);
            $expiration_date = strtotime("-3 months");
            if ($password_change_date <= $expiration_date) {
               $response = '3';
            }
            return $response;
         }
         return $response;
      }else{
         return $response;
      }
   }
  // Function to unlock a locked user account after five minutes
   function lockAccount() {    
      global $db ,$link;
      $response = '';
      $logintime   = date("Y-m-d H:i:s");
      $username   = ($_POST['loginID']);
      $query="SELECT locked_count,last_attemped_time,I_UserID FROM $db.tbl_mst_user_company WHERE V_EmailID='$username' and I_UserStatus='1'";
      $result = mysqli_query($link,$query);
      $num_rows=mysqli_num_rows($result); 
      $locked_count_plus = '';
      if($num_rows==1){
         $row =  mysqli_fetch_array($result);
         $locked_count  =  $row['locked_count'];
         $userid        =  $row['I_UserID'];   
         $locked_time =  $row['last_attemped_time']; 
         $time_last = date("H:i:s",strtotime($locked_time));  
         $difference = time() - strtotime($time_last);
         if ($locked_count>'3' && $difference > 300){
            $sqlrest = "UPDATE $dbname.tbl_mst_user_company SET locked_count = '1' , last_attemped_time = '$logintime' where I_UserID='$userid'";
            mysqli_query($link, $sqlrest);
            return $response;
         }
         if($locked_count>'3'){
            $response = '1';
            return $response;
         }else{
            if($locked_count == 0){
               $locked_count_plus = 1;
            }else if($locked_count>=1){
               $locked_count_plus = $locked_count+1;
            }
            $sqlrest = "UPDATE $dbname.tbl_mst_user_company SET locked_count = '$locked_count_plus' , last_attemped_time = '$logintime' where I_UserID='$userid'";
            mysqli_query($link, $sqlrest);
            return $response;
         }
      }else{
         return $response;
      }
   }
   /*** Maximum ID from table ***/
   function maximum_id($table_name,$field_name){
      global $link,$db;
      $sql_id = "select max($field_name) as max_id from $db.$table_name";
      $Fetch_Id=mysqli_query($link,$sql_id);
      if($row=mysqli_fetch_array($Fetch_Id)){
         return $max_id=$row['max_id']+1;
      }else{
         return $max_id=1;
      }
   }
   /*** Function to log failed login attempts ***/
   function failed_login($table_name,$usname,$reason_failure,$db){
      global $link;
      mysqli_select_db($link,$db);
      $modificationtime    =  date("Y-m-d G:i:s");
      $ip =getenv('REMOTE_ADDR');
      $id=maximum_id($table_name,'SNo');
      if(empty($reason_failure)){ $reason_failure="login"; }
      $sql="insert into $table_name(SNo,IP,AccessedAt,UserName,Reason) values('$id','$ip','$modificationtime','$usname','$reason_failure')";
      $res=mysqli_query($link,$sql) or die(mysqli_error($link)) ;
   }

   // Function to check if a user is active :: farhan akhtar [15-03-2025]
   function isUserActive($link, $username) {
    global $link,$db;
    // Use prepared statements for improved security
    $query = "SELECT AtxUserStatus FROM $db.uniuserprofile WHERE AtxEmail = ? LIMIT 1";
    $stmt = mysqli_prepare($link, $query);

    mysqli_stmt_bind_param($stmt, "s", $username);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);

    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        return $row['AtxUserStatus']; // Adjust condition if status logic changes
    }

    return false; // User not found or inactive
   }

   // get username from email 
   function getUserName($link, $email) {
    global $link,$db;
      // Use prepared statements for improved security
      $query = "SELECT AtxUserName FROM $db.uniuserprofile WHERE AtxEmail = ? AND AtxUserStatus = 1 LIMIT 1";
      $stmt = mysqli_prepare($link, $query);

      mysqli_stmt_bind_param($stmt, "s", $email);
      mysqli_stmt_execute($stmt);
      $result = mysqli_stmt_get_result($stmt);

      if ($result && mysqli_num_rows($result) > 0) {
         $row = mysqli_fetch_assoc($result);
         return trim($row['AtxUserName']); // Adjust condition if status logic changes
      }

      return false; 
   }


   // FREE SITTING AND FIX SITTING {farhan akhtar :: 03-04-2025}

   function getUserIP($link, $username) {
    global $link,$db;
      // Original prepared statement query
      $query = "SELECT IP_Address FROM $db.encryp1 WHERE UserName = ? AND Status = 1";
  
      // Print the interpolated query for testing
      // $debugQuery = str_replace("?", "'$username'", $query);
      // echo "DEBUG SQL: $debugQuery\n";
  
      // Continue with the prepared statement execution
      $stmt = mysqli_prepare($link, $query);
      mysqli_stmt_bind_param($stmt, "s", $username);
      mysqli_stmt_execute($stmt);
      $result = mysqli_stmt_get_result($stmt);
  
      if ($result && mysqli_num_rows($result) > 0) {
          $row = mysqli_fetch_assoc($result);
          return $row['IP_Address'];
      }
  
      return false;
  }
  // if password not match in db update currect ldap password in table
  // Correct Password Update Function (Your System) - 07-03-2026,Aarti
  function updateUserPassword($userId, $hashedPassword, $db){

    $sql = "UPDATE tbl_mst_user_company
            SET V_Password = ?,
                password_change_date = NOW()
            WHERE I_UserID = ?";

    $stmt = mysqli_prepare($db, $sql);
    mysqli_stmt_bind_param($stmt, "si", $hashedPassword, $userId);

    if(mysqli_stmt_execute($stmt)){
        return true;
    }

    return false;
}
?>