<?php
require_once 'auth.php';
include 'db.php';
requireLogin($conn, ['superadmin']);

// ✅ PROSES EDIT USER (dari edit_user.php)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['user_id'])) {
    
    $uid = intval($_POST['user_id']);
    $fullname = trim($_POST['fullname'] ?? '');
    $short_name = trim($_POST['short_name'] ?? '');
    if ($short_name === '') {
        $short_name = $fullname;
    }
    $email = trim($_POST['email'] ?? '');
    $department = trim($_POST['department'] ?? '');
    $role = $_POST['role'] ?? 'user';
    $status = $_POST['status'] ?? 'approved';
    
    // 🔐 Elak edit superadmin lain
    $check = mysqli_prepare($conn, "SELECT email, role FROM users WHERE id = ?");
    mysqli_stmt_bind_param($check, "i", $uid);
    mysqli_stmt_execute($check);
    $target = mysqli_fetch_assoc(mysqli_stmt_get_result($check));
    
    if ($target && !($target['role']==='superadmin' && $target['email']!==$_SESSION['email'])) {
        
        // ✅ Kemaskini SEMUA field termasuk role & status
        $update = mysqli_prepare($conn, "UPDATE users SET fullname=?, short_name=?, email=?, department=?, role=?, status=? WHERE id=?");
        mysqli_stmt_bind_param($update, "ssssssi", $fullname, $short_name, $email, $department, $role, $status, $uid);
        
        if (mysqli_stmt_execute($update)) {
            logActivity(
                $conn,
                (int) ($_SESSION['user_id'] ?? 0),
                'update_user',
                'Kemaskini user: ' . $fullname . ' (' . $email . ') - Role: ' . $role . ', Status: ' . $status . ' (User ID: ' . $uid . ')'
            );
            header("Location: user_list.php?success=updated");
        } else {
            header("Location: edit_user.php?id={$uid}&error=update_failed");
        }
        
    } else {
        header("Location: user_list.php?error=cannot_edit_superadmin");
    }
    exit();
}

// ✅ PROSES BULK APPROVE/REJECT (dari user_approval.php)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action'], $_POST['user_ids']) && is_array($_POST['user_ids'])) {
    
    $action = $_POST['bulk_action'];
    $new_status = ($action === 'approve') ? 'approved' : 'rejected';
    $user_ids = array_map('intval', $_POST['user_ids']);
    
    if (!empty($user_ids)) {
        $placeholders = implode(',', array_fill(0, count($user_ids), '?'));
        $stmt = mysqli_prepare($conn, "UPDATE users SET status = ? WHERE id IN ($placeholders)");
        $types = 's' . str_repeat('i', count($user_ids));
        mysqli_stmt_bind_param($stmt, $types, $new_status, ...$user_ids);
        if (mysqli_stmt_execute($stmt)) {
            logActivity(
                $conn,
                (int) ($_SESSION['user_id'] ?? 0),
                'update_user_status_bulk',
                'Kelulusan user pukal: ' . $action . ' kepada ' . count($user_ids) . ' user (ID: ' . implode(', ', $user_ids) . ')'
            );
        }
    }
    
    header("Location: user_approval.php?success=bulk_" . $action);
    exit();
}

// Default redirect
header("Location: user_list.php");
exit();
?>
