<?php
/**
 * BIS Campaign - post-login session setup.
 * Completes the session after credentials are validated in login_flow.php.
 */
session_start();

include __DIR__ . "/config/web_mysqlconnect.php";
include __DIR__ . "/function/MultiTanentDBValidation.php";

if (!isset($_SESSION['TEMP_LOGIN'])) {
    header("Location: web_login.php");
    exit;
}

$type   = $_GET['type'] ?? 'campaign';
$userid = (int) $_SESSION['TEMP_USERID'];

if ($type !== 'campaign') {
    header("Location: web_login.php");
    exit;
}

$db = $_SESSION['database'] ?? 'ensembler';

$stmt = mysqli_prepare(
    $link,
    "SELECT I_UserID, I_UserStatus, V_EmailID, I_FirstLogin, I_CompanyID
     FROM $db.tbl_mst_user_company WHERE I_UserID = ?"
);
mysqli_stmt_bind_param($stmt, "i", $userid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

if (mysqli_num_rows($result) !== 1) {
    header("Location: web_login.php");
    exit;
}

$row = mysqli_fetch_assoc($result);
$company_id = $row['I_CompanyID'];

$stmt = mysqli_prepare(
    $link,
    "SELECT AtxUserName, File_up, AtxDesignation, AtxEmail, AtxDisplayName, i_classify
     FROM $db.uniuserprofile WHERE AtxUserID = ?"
);
mysqli_stmt_bind_param($stmt, "i", $userid);
mysqli_stmt_execute($stmt);
$profile = mysqli_stmt_get_result($stmt)->fetch_assoc();

$user_name = $profile['AtxUserName'];

failed_login('logip', $user_name, 'login', $db);
$q = mysqli_fetch_array(mysqli_query($link, "SELECT SNo FROM $db.logip ORDER BY SNo DESC LIMIT 1"));
$_SESSION['SNo'] = $q['SNo'];

$now = date("Y-m-d H:i:s");
mysqli_query($link, "UPDATE $db.uniuserprofile SET login_status='online', login_datetime='$now' WHERE AtxUserID='$userid'");
mysqli_query($link, "UPDATE $db.tbl_mst_user_company SET locked_count='0' WHERE I_UserID='$userid'");

$res_group = mysqli_query($link, "SELECT atxGid FROM $db.unigroupdetails WHERE ugdContactID='$userid'");
$row_group = mysqli_fetch_array($res_group);
$user_group = $row_group['atxGid'];

$_SESSION['userid']        = $userid;
$_SESSION['logged']        = ucfirst($user_name);
$_SESSION['full_name']     = $profile['AtxDisplayName'];
$_SESSION['login_email']   = $profile['AtxEmail'];
$_SESSION['user_image']    = $profile['File_up'];
$_SESSION['branch']        = '1459';
$_SESSION['companyid']     = $company_id;
$_SESSION['user_group']    = $user_group;
$_SESSION['database']      = $db;
$_SESSION['reginoal_spoc'] = $profile['AtxDesignation'];

$DBcreds = [
    "configdbhost" => configdbhost,
    "configdbuser" => configdbuser,
    "configdbpass" => configdbpass,
];
$DBresponse = getDatabaseForCompany($company_id, $DBcreds);
if ($DBresponse['status']) {
    $_SESSION['database']    = $DBresponse['database_name'];
    $_SESSION['campaign']    = $DBresponse['campaign_name'];
    $_SESSION['companyName'] = $DBresponse['company_name'];
    $db = $DBresponse['database_name'];
}

unset($_SESSION['TEMP_LOGIN'], $_SESSION['TEMP_USERID'], $_SESSION['TEMP_EMAIL'], $_SESSION['TEMP_COMPANY']);

add_audit_log($userid, 'loggedin', 'null', 'BIS Campaign login success', $db);

$web_consumer_home = base64_encode('web_consumer_home');
header("Location: CRM/customer_index.php?token=$web_consumer_home");
exit;

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 $row['max_id'] + 1;
    }
    return 1;
}

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')";
    mysqli_query($link, $sql) or die(mysqli_error($link));
}

function add_audit_log($user_id, $actionlog, $ticketid, $comments, $db, $types = '')
{
    global $link, $db;
    $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() . 'Err web_audit_history');
}
