MMCT TEAM
Server IP : 217.21.85.138  /  Your IP : 216.73.216.103
Web Server : LiteSpeed
System : Linux in-mum-web906.main-hosting.eu 4.18.0-553.37.1.lve.el8.x86_64 #1 SMP Mon Feb 10 22:45:17 UTC 2025 x86_64
User : u915722082 ( 915722082)
PHP Version : 7.4.33
Disable Function : system, exec, shell_exec, passthru, mysql_list_dbs, ini_alter, dl, symlink, link, chgrp, leak, popen, apache_child_terminate, virtual, mb_send_mail
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : OFF  |  Python : OFF
Directory (0755) :  /home/u915722082/public_html/apitodshut/../projects/admin/

[  Home  ][  C0mmand  ][  Upload File  ]

Current File : /home/u915722082/public_html/apitodshut/../projects/admin/user_actions.php
<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

require_once '../config/config.php';
require_once '../config/db.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$autoload_paths = [
    '../vendor/autoload.php',
    '../../vendor/autoload.php',
    '../../../vendor/autoload.php'
];

foreach ($autoload_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        break;
    }
}

$action = $_POST['action'] ?? '';
$current_user_id = $_SESSION['admin_id'];
$current_user_role = $_SESSION['role'] ?? 'Employee';

// ✅ Only CEO and Manager can manage users
if ($current_user_role === 'Employee') {
    echo json_encode(['success' => false, 'message' => 'You do not have permission to manage users']);
    exit;
}

try {
    switch ($action) {
        case 'add':
            addUser($con, $current_user_id, $current_user_role);
            break;
            
        case 'edit':
            editUser($con, $current_user_id, $current_user_role);
            break;
            
        case 'delete':
            deleteUser($con, $current_user_id, $current_user_role);
            break;
            
        default:
            throw new Exception('Invalid action');
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

function addUser($con, $creator_id, $creator_role) {
    $fname = trim($_POST['fname'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $role = $_POST['role'] ?? '';
    
    // ✅ PERMISSION CHECK: Manager can only add Employees
    if ($creator_role === 'Manager' && $role !== 'Employee') {
        throw new Exception('Managers can only add Employees. Only CEO can add Managers or other CEOs.');
    }
    
    if (empty($fname) || empty($email) || empty($password) || empty($role)) {
        throw new Exception('All fields are required');
    }
    
    if (strlen($password) < 6) {
        throw new Exception('Password must be at least 6 characters');
    }
    
    // Check if email already exists
    $check_stmt = mysqli_prepare($con, "SELECT uid FROM tbl_user WHERE email = ?");
    mysqli_stmt_bind_param($check_stmt, "s", $email);
    mysqli_stmt_execute($check_stmt);
    mysqli_stmt_store_result($check_stmt);
    
    if (mysqli_stmt_num_rows($check_stmt) > 0) {
        mysqli_stmt_close($check_stmt);
        throw new Exception('Email already exists');
    }
    mysqli_stmt_close($check_stmt);
    
    // Hash password
    $hashed_password = password_hash($password, PASSWORD_BCRYPT);
    
    // Insert user
    $stmt = mysqli_prepare($con, 
        "INSERT INTO tbl_user (fname, email, password, role, status, created_by) 
         VALUES (?, ?, ?, ?, 'active', ?)"
    );
    
    mysqli_stmt_bind_param($stmt, "ssssi", $fname, $email, $hashed_password, $role, $creator_id);
    
    if (mysqli_stmt_execute($stmt)) {
        mysqli_stmt_close($stmt);
        
        // Send email
        sendWelcomeEmail($email, $fname, $password, $role);
        
        echo json_encode(['success' => true, 'message' => 'User added successfully']);
    } else {
        mysqli_stmt_close($stmt);
        throw new Exception('Failed to add user');
    }
}

function editUser($con, $editor_id, $editor_role) {
    $user_id = intval($_POST['user_id'] ?? 0);
    $new_role = $_POST['role'] ?? '';
    
    if ($user_id <= 0 || empty($new_role)) {
        throw new Exception('Invalid data');
    }
    
    // ✅ Get the target user's current role
    $check_stmt = mysqli_prepare($con, "SELECT role FROM tbl_user WHERE uid = ?");
    mysqli_stmt_bind_param($check_stmt, "i", $user_id);
    mysqli_stmt_execute($check_stmt);
    $check_result = mysqli_stmt_get_result($check_stmt);
    $target_user = mysqli_fetch_assoc($check_result);
    mysqli_stmt_close($check_stmt);
    
    if (!$target_user) {
        throw new Exception('User not found');
    }
    
    // ✅ PERMISSION CHECK: Manager CANNOT edit CEO
    if ($editor_role === 'Manager' && $target_user['role'] === 'CEO') {
        throw new Exception('Managers cannot update CEO accounts. Only CEO can update other CEOs.');
    }
    
    // ✅ PERMISSION CHECK: Manager CANNOT promote to CEO or Manager
    if ($editor_role === 'Manager' && ($new_role === 'CEO' || $new_role === 'Manager')) {
        throw new Exception('Managers can only assign Employee role. Only CEO can assign CEO or Manager roles.');
    }
    
    // ✅ PERMISSION CHECK: Manager CANNOT edit other Managers
    if ($editor_role === 'Manager' && $target_user['role'] === 'Manager') {
        throw new Exception('Managers cannot update other Manager accounts. Only CEO can update Managers.');
    }
    
    // Update user role
    $stmt = mysqli_prepare($con, "UPDATE tbl_user SET role = ? WHERE uid = ?");
    mysqli_stmt_bind_param($stmt, "si", $new_role, $user_id);
    
    if (mysqli_stmt_execute($stmt)) {
        mysqli_stmt_close($stmt);
        echo json_encode(['success' => true, 'message' => 'User role updated successfully']);
    } else {
        mysqli_stmt_close($stmt);
        throw new Exception('Failed to update user');
    }
}

function deleteUser($con, $deleter_id, $deleter_role) {
    $user_id = intval($_POST['user_id'] ?? 0);
    
    if ($user_id <= 0) {
        throw new Exception('Invalid user ID');
    }
    
    // ✅ Get the target user's role
    $check_stmt = mysqli_prepare($con, "SELECT role FROM tbl_user WHERE uid = ?");
    mysqli_stmt_bind_param($check_stmt, "i", $user_id);
    mysqli_stmt_execute($check_stmt);
    $check_result = mysqli_stmt_get_result($check_stmt);
    $target_user = mysqli_fetch_assoc($check_result);
    mysqli_stmt_close($check_stmt);
    
    if (!$target_user) {
        throw new Exception('User not found');
    }
    
    // ✅ PERMISSION CHECK: Manager CANNOT delete CEO
    if ($deleter_role === 'Manager' && $target_user['role'] === 'CEO') {
        throw new Exception('Managers cannot delete CEO accounts. Only CEO can delete other CEOs.');
    }
    
    // ✅ PERMISSION CHECK: Manager CANNOT delete other Managers
    if ($deleter_role === 'Manager' && $target_user['role'] === 'Manager') {
        throw new Exception('Managers cannot delete other Manager accounts. Only CEO can delete Managers.');
    }
    
    // Delete user
    $stmt = mysqli_prepare($con, "DELETE FROM tbl_user WHERE uid = ?");
    mysqli_stmt_bind_param($stmt, "i", $user_id);
    
    if (mysqli_stmt_execute($stmt)) {
        mysqli_stmt_close($stmt);
        echo json_encode(['success' => true, 'message' => 'User deleted successfully']);
    } else {
        mysqli_stmt_close($stmt);
        throw new Exception('Failed to delete user');
    }
}

function sendWelcomeEmail($to_email, $name, $password, $role) {
    if (!class_exists('PHPMailer\PHPMailer\PHPMailer')) {
        return false;
    }
    
    try {
        $mail = new PHPMailer(true);
        
        $mail->SMTPDebug = 0;
        $mail->isSMTP();
        $mail->Host = SMTP_HOST;
        $mail->SMTPAuth = true;
        $mail->Username = SMTP_USERNAME;
        $mail->Password = SMTP_PASSWORD;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = SMTP_PORT;
        $mail->CharSet = 'UTF-8';
        
        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );
        
        $mail->setFrom(SMTP_FROM_EMAIL, SMTP_FROM_NAME);
        $mail->addAddress($to_email, $name);
        $mail->addReplyTo(SMTP_FROM_EMAIL, SMTP_FROM_NAME);
        
        $mail->isHTML(true);
        $mail->Subject = 'Welcome to TDS Admin Hub - Account Created';
        
        $mail->Body = "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
        </head>
        <body style='font-family: Arial, sans-serif; line-height: 1.6;margin: 0; padding: 0;'>
            <div style='max-width: 600px; margin: 20px auto; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 10px rgba(0,0,0,0.1);'>
                <div style='background:#000; color: white; padding: 30px; text-align: center;'>
                    <h1 style='margin:0; font-size: 24px;'>Welcome to TDS Admin Hub!</h1>
                </div>
                <div style='padding: 30px;'>
                    <h2 style='color: #333; margin-top: 0;'>Hello $name,</h2>
                    <p>Your account has been created successfully. Here are your login credentials:</p>
                    
                    <div style='background: #f8f9fa; padding: 20px; margin: 20px 0; border-left: 4px solid #000; border-radius: 4px;'>
                        <p style='margin: 5px 0;'><strong>Email:</strong> $to_email</p>
                        <p style='margin: 5px 0;'><strong>Password:</strong> $password</p>
                        <p style='margin: 5px 0;'><strong>Role:</strong> $role</p>
                    </div>
                    
                    <p style='color: #f1416c;'><strong>Important:</strong> Please change your password after your first login.</p>
                    
                    <div style='text-align: center; margin: 30px 0;'>
                        <a href='" . (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://{$_SERVER['HTTP_HOST']}/admin/login.php' 
                           style='background: #000; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; display: inline-block;'>
                            Login Now
                        </a>
                    </div>
                    
                    <p>Best regards,<br><strong>TDS Projects Team</strong></p>
                </div>
                <div style='text-align: center; padding: 20px; color: #666; font-size: 14px; background: #f8f9fa;'>
                    <p>&copy; " . date('Y') . " TheDotStudios. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>
        ";
        
        $mail->AltBody = "Welcome to TDS Admin Hub!\n\nYour login credentials:\nEmail: $to_email\nPassword: $password\nRole: $role";
        
        $mail->send();
        return true;
        
    } catch (Exception $e) {
        error_log("Email Error: " . $e->getMessage());
        return false;
    }
}
?>

MMCT - 2023