<?php
ob_start();
/************************************************************************/
/*     PROGRAMMER     :  SMA                                            */
/*     SCRIPT NAME    :  adminusers_manage.php                          */
/*     CREATED ON     :  10/JULY/2006                                   */
/*     UPDATED BY     :  ChatGPT Modernization (2025)                   */
/************************************************************************/

include_once '../includes/session.php';
include '../includes/constants.php';
include '../includes/functions.php';
include_once '../includes/function1.php';
include_once '../includes/allstripslashes.php';

$partners = new partners();
$partners->connection($host, $user, $pass, $db);

$commonobj = new common();
$adminobj = new adminuser();

// Getting and sanitizing values
$id         = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
$username   = isset($_POST['txt_username']) ? trim($_POST['txt_username']) : '';
$email      = isset($_POST['txt_email']) ? trim($_POST['txt_email']) : '';
$password   = isset($_POST['txt_password']) ? trim($_POST['txt_password']) : '';
$chk_mail   = isset($_POST['chk_mail']) ? true : false;
$mode       = isset($_REQUEST['mode']) ? trim($_REQUEST['mode']) : '';

// Redirect URL construction
$returnstring = "txt_username=" . urlencode($username) . "&txt_email=" . urlencode($email);
if (!empty($password)) {
    $returnstring .= "&txt_password=" . urlencode($password);
}
$returnUrl = $id ? "index.php?Act=adminuser_edit&id=$id&$returnstring" : "index.php?Act=adminusers&$returnstring";

// Delete selected Admin User
if ($mode === 'delete') {
    if (!$adminobj->DeleteAdminUser($id)) {
        $msg = urlencode("Unknown error! Deletion Failed");
    } else {
        $msg = urlencode("Admin User Deleted Successfully");

        // Deleting Admin Privileges
        $adminobj->GetAllAdminLinks();
        for ($i = 0; $i < count($adminobj->linkid); $i++) {
            $linkid = $adminobj->linkid[$i];
            $users = $adminobj->linkusers[$i];
            $userlist = explode(",", $users);
            $userlist = array_filter($userlist, function ($val) use ($id) {
                return trim($val) != $id;
            });
            $newusers = implode(",", $userlist);
            $adminobj->UpdateAdminUserLinks($linkid, $newusers);
        }
    }

    header("Location: index.php?Act=adminusers&msg=$msg");
    exit;
}

// Validate required fields
$validatestring = $username . "~*" . $email . "~*" . $password;
if ($commonobj->nullvalidation($validatestring)) {
    $msg = urlencode("Don't leave fields blank");
    header("Location: $returnUrl&msg=$msg");
    exit;
}

// Username validation
if (!$adminobj->IsUserNameExists($username, $id)) {
    $msg = urlencode("User Name already exists");
    header("Location: $returnUrl&msg=$msg");
    exit;
}

// Email validation
if ($partners->is_email($email) == 0) {
    $msg = urlencode("Enter a valid Email Address");
    header("Location: $returnUrl&msg=$msg");
    exit;
}

if (!$adminobj->IsEmailexists($email, $id)) {
    $msg = urlencode("Email Address already exists");
    header("Location: $returnUrl&msg=$msg");
    exit;
}

// Process add or edit
if ($id && $mode === 'edit') {
    // Update admin user
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
    if (!$adminobj->UpdateAdminUser($id, $username, $email, $hashedPassword)) {
        $msg = urlencode("Unknown error! Updation Failed");
        header("Location: $returnUrl&msg=$msg");
        exit;
    }

    $msg = urlencode("Admin User Details Updated Successfully");

    if ($chk_mail && $adminobj->GetSuperAdmin()) {
        $to = $email;
        $subject = "Admin User Details Updated";
        $from = $adminobj->admin_email;
        $adminheader = $adminobj->admin_header;
        $adminfooter = $adminobj->admin_footer;
        $adminobj->SendMailtoAdminUser($to, $subject, $from, $adminheader, $username, '[hidden for security]', $adminfooter);
    }
} else {
    // Insert new user
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
    if (!$adminobj->AddAdminUser($username, $email, $hashedPassword)) {
        $msg = urlencode("Unknown error! Insertion Failed");
        header("Location: $returnUrl&msg=$msg");
        exit;
    }

    $msg = urlencode("Admin User Added Successfully");

    if ($chk_mail && $adminobj->GetSuperAdmin()) {
        $to = $email;
        $subject = "Registered as Admin User";
        $from = $adminobj->admin_email;
        $adminheader = $adminobj->admin_header;
        $adminfooter = $adminobj->admin_footer;
        $adminobj->SendMailtoAdminUser($to, $subject, $from, $adminheader, $username, '[hidden for security]', $adminfooter);
    }
}

header("Location: index.php?Act=adminusers&msg=$msg");
exit;
?>
