<?php
session_start();
require_once '../config/db.php';

header('Content-Type: application/json');

$is_admin = isset($_SESSION['admin_id']);
$is_ac = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'AC';
$is_aac = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'AAC';
$is_officer_role = $is_ac || $is_aac; // AC and AAC are officers

if (!$is_admin && !$is_officer_role) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$action = $_POST['action'] ?? '';
$id = $_POST['id'] ?? null;

// Only require ID for actions that need it (not for create_user)
$actionsRequiringId = ['approve', 'reject', 'update_status', 'update_profile', 'delete', 'remove_temp', 'remove_ac', 'officer_update_member'];
if (in_array($action, $actionsRequiringId) && !$id) {
    echo json_encode(['success' => false, 'message' => 'Missing User ID']);
    exit;
}

// Helper function to log activities
function logActivity($pdo, $referenceType, $referenceId, $description, $status, $performedByRole, $performedByUserId = null, $performedByAdminId = null)
{
    $stmt = $pdo->prepare("
        INSERT INTO activity_logs (reference_type, reference_id, description, status, performed_by_role, performed_by_user_id, performed_by_admin_id) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([$referenceType, $referenceId, $description, $status, $performedByRole, $performedByUserId, $performedByAdminId]);
}

try {
    // Ensure removed_accounts table exists (for temporary removals)
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS removed_accounts (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            removal_type ENUM('temporary','permanent') NOT NULL DEFAULT 'temporary',
            signature VARCHAR(255) NULL,
            removed_by_admin_id INT NULL,
            removed_by_user_id INT NULL,
            removed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
        )
    ");

    // Attempt to add removed_by_user_id if it doesn't exist
    try {
        $pdo->exec("ALTER TABLE removed_accounts ADD COLUMN removed_by_user_id INT NULL AFTER removed_by_admin_id");
    } catch (Exception $e) {
        // Column already exists, ignore
    }

    // Ensure activity_logs table exists
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS activity_logs (
            id INT AUTO_INCREMENT PRIMARY KEY,
            reference_type VARCHAR(50) NOT NULL,
            reference_id INT NULL,
            description TEXT NOT NULL,
            status VARCHAR(50) NOT NULL,
            performed_by_role VARCHAR(20) NOT NULL,
            performed_by_user_id INT NULL,
            performed_by_admin_id INT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_created_at (created_at),
            INDEX idx_performed_by (performed_by_role, performed_by_user_id, performed_by_admin_id)
        )
    ");

    if ($action === 'approve') {
        $role = $_POST['role'] ?? 'R.O';
        $area = $_POST['area'] ?? '';

        // Get pending user (must be in same area as officer when AC/AAC)
        $stmtUser = $pdo->prepare("SELECT first_name, last_name, nroi_id, area, status FROM users WHERE id = ?");
        $stmtUser->execute([$id]);
        $userInfo = $stmtUser->fetch(PDO::FETCH_ASSOC);
        if (!$userInfo || $userInfo['status'] !== 'pending') {
            echo json_encode(['success' => false, 'message' => 'User not found or not pending']);
            exit;
        }

        if ($is_admin) {
            // Admin: can set role, area, and rank
            $rankInput = $_POST['rank'] ?? 'Regular'; // rank column stores OJT/Regular status
            $rank = in_array(strtoupper($rankInput), ['REGULAR', 'OJT', 'INTERN']) ? (strtoupper($rankInput) === 'REGULAR' ? 'Regular' : strtoupper($rankInput)) : 'Regular';
            if (!in_array($role, ['R.O', 'C.R.O', 'AC', 'AAC', 'RM', 'NROI', 'PPSA'])) {
                throw new Exception("Invalid role selection");
            }
            if (!in_array($rank, ['Regular', 'OJT'])) {
                throw new Exception("Invalid status selection");
            }
            if (empty($area) && $role !== 'RM') {
                throw new Exception("Area assignment is required");
            }
            $stmt = $pdo->prepare("UPDATE users SET status = 'approved', role = ?, area = ?, rank = ? WHERE id = ?");
            $stmt->execute([$role, $area, $rank, $id]);
            $performedByRole = 'ADMIN';
            $performedByAdminId = $_SESSION['admin_id'];
            $performedByUserId = null;
            $description = "Approved user account: " . ($userInfo['first_name'] ?? '') . " " . ($userInfo['last_name'] ?? '') . " (NROI ID: " . ($userInfo['nroi_id'] ?? 'N/A') . ") - Assigned role: {$role}, Area: {$area}, Status: {$rank}";
        } else {
            // AC/AAC: can only approve users in their area; keep applicant's chosen area, but allow setting role/rank
            $officerArea = trim($_SESSION['area'] ?? '');
            $userArea = trim($userInfo['area'] ?? '');
            if (empty($officerArea) || $userArea !== $officerArea) {
                echo json_encode(['success' => false, 'message' => 'You can only approve applications for your area.']);
                exit;
            }
            $area = $userInfo['area']; // keep area from application
            $role = $_POST['role'] ?? 'R.O';
            $rankInput = $_POST['rank'] ?? 'Regular';
            $rank = in_array(strtoupper($rankInput), ['REGULAR', 'OJT', 'INTERN']) ? (strtoupper($rankInput) === 'REGULAR' ? 'Regular' : strtoupper($rankInput)) : 'Regular';

            // Security: limit roles that officers can assign
            $allowedRoles = ['R.O', 'C.R.O'];
            if ($is_ac) {
                $allowedRoles[] = 'AAC';
            }
            if (!in_array($role, $allowedRoles)) {
                $role = 'R.O';
            }
            if (!in_array(strtoupper($rank), ['REGULAR', 'OJT', 'INTERN'])) {
                $rank = 'Regular';
            }
            $area = $userInfo['area']; // keep area from application (already verified above matches officer's area)

            $stmt = $pdo->prepare("UPDATE users SET status = 'approved', role = ?, rank = ? WHERE id = ?");
            $stmt->execute([$role, $rank, $id]);
            $performedByRole = $is_ac ? 'AC' : 'AAC';
            $performedByAdminId = null;
            $performedByUserId = $_SESSION['user_id'] ?? null;
            $description = "Approved user account: " . ($userInfo['first_name'] ?? '') . " " . ($userInfo['last_name'] ?? '') . " (NROI ID: " . ($userInfo['nroi_id'] ?? 'N/A') . ") - Assigned Rank: {$role}, Area: {$area}, Status: {$rank}";
        }

        logActivity($pdo, 'user', $id, $description, 'approved', $performedByRole, $performedByUserId, $performedByAdminId);
        echo json_encode(['success' => true, 'message' => 'User approved.']);

    } elseif ($action === 'reject') {
        // Both Admin and Officers (AC/AAC) can reject pending users. AC/AAC only in their area.
        $stmtUser = $pdo->prepare("SELECT first_name, last_name, nroi_id, area FROM users WHERE id = ? AND status = 'pending'");
        $stmtUser->execute([$id]);
        $userInfo = $stmtUser->fetch(PDO::FETCH_ASSOC);
        if (!$userInfo) {
            echo json_encode(['success' => false, 'message' => 'User not found or not pending']);
            exit;
        }
        if (!$is_admin) {
            $officerArea = trim($_SESSION['area'] ?? '');
            $userArea = trim($userInfo['area'] ?? '');
            if ($officerArea === '' || $userArea !== $officerArea) {
                echo json_encode(['success' => false, 'message' => 'You can only reject applications for your area.']);
                exit;
            }

            // Enforce role boundaries for officers
            $targetUserRole = $userInfo['role'] ?? 'member';
            if ($is_ac) {
                $canHandle = in_array($targetUserRole, ['AAC', 'R.O', 'C.R.O', 'RO', 'CRO', 'member', '']);
            } else { // is_aac
                $canHandle = in_array($targetUserRole, ['R.O', 'C.R.O', 'RO', 'CRO', 'member', '']);
            }
            if (!$canHandle) {
                echo json_encode(['success' => false, 'message' => 'You do not have permission to reject this account type.']);
                exit;
            }
        }
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ? AND status = 'pending'");
        $stmt->execute([$id]);
        if ($stmt->rowCount() > 0) {
            // Log activity
            $performedByRole = $is_admin ? 'ADMIN' : ($is_ac ? 'AC' : ($is_aac ? 'AAC' : 'UNKNOWN'));
            $performedByAdminId = $is_admin ? $_SESSION['admin_id'] : null;
            $performedByUserId = !$is_admin ? ($_SESSION['user_id'] ?? null) : null;
            $description = "Rejected pending user account: " . ($userInfo['first_name'] ?? '') . " " . ($userInfo['last_name'] ?? '') . " (NROI ID: " . ($userInfo['nroi_id'] ?? 'N/A') . ")";
            logActivity($pdo, 'user', $id, $description, 'rejected', $performedByRole, $performedByUserId, $performedByAdminId);

            echo json_encode(['success' => true, 'message' => 'User account rejected and permanently deleted']);
        } else {
            throw new Exception("User not found or cannot be rejected");
        }

    } elseif ($action === 'update_status') {
        $status = $_POST['status'] ?? '';
        if (!in_array($status, ['pending', 'approved', 'deactivated', 'rejected'])) {
            throw new Exception("Invalid status");
        }

        // Get user info for logging and security checks
        $stmtUser = $pdo->prepare("SELECT first_name, last_name, nroi_id, area, role FROM users WHERE id = ?");
        $stmtUser->execute([$id]);
        $userInfo = $stmtUser->fetch(PDO::FETCH_ASSOC);

        if (!$userInfo) {
            throw new Exception("User not found.");
        }

        if (!$is_admin) {
            $officerArea = trim($_SESSION['area'] ?? '');
            $userArea = trim($userInfo['area'] ?? '');
            if ($officerArea === '' || $userArea !== $officerArea) {
                echo json_encode(['success' => false, 'message' => 'You can only update users in your area.']);
                exit;
            }

            // Enforce role boundaries for officers
            $targetUserRole = $userInfo['role'] ?? 'member';
            if ($is_ac) {
                $canHandle = in_array($targetUserRole, ['AAC', 'R.O', 'C.R.O', 'RO', 'CRO', 'member', '']);
            } else { // is_aac
                $canHandle = in_array($targetUserRole, ['R.O', 'C.R.O', 'RO', 'CRO', 'member', '']);
            }
            if (!$canHandle) {
                echo json_encode(['success' => false, 'message' => 'You do not have permission to manage this account type.']);
                exit;
            }
        }

        $stmt = $pdo->prepare("UPDATE users SET status = ? WHERE id = ?");
        $stmt->execute([$status, $id]);

        // Log activity
        $performedByRole = $is_admin ? 'ADMIN' : ($is_ac ? 'AC' : ($is_aac ? 'AAC' : 'UNKNOWN'));
        $performedByAdminId = $is_admin ? $_SESSION['admin_id'] : null;
        $performedByUserId = !$is_admin ? ($_SESSION['user_id'] ?? null) : null;
        $description = "Updated status of user: " . ($userInfo['first_name'] ?? '') . " " . ($userInfo['last_name'] ?? '') . " (NROI ID: " . ($userInfo['nroi_id'] ?? 'N/A') . ") to {$status}";
        logActivity($pdo, 'user', $id, $description, $status, $performedByRole, $performedByUserId, $performedByAdminId);

        echo json_encode(['success' => true, 'message' => 'User status updated successfully']);

    } elseif ($action === 'officer_update_member') {
        // AC/AAC can update role and rank of approved members in their area only
        if ($is_admin) {
            echo json_encode(['success' => false, 'message' => 'Use Accounts page to update.']);
            exit;
        }
        $officerArea = $_SESSION['area'] ?? '';
        if ($officerArea === '') {
            echo json_encode(['success' => false, 'message' => 'Your area is not set.']);
            exit;
        }
        $role = trim($_POST['role'] ?? 'R.O');
        $rankInput = trim($_POST['rank'] ?? 'Regular');
        $rank = in_array(strtoupper($rankInput), ['REGULAR', 'OJT', 'INTERN']) ? (strtoupper($rankInput) === 'REGULAR' ? 'Regular' : strtoupper($rankInput)) : 'Regular';
        if (!in_array($role, ['R.O', 'C.R.O', 'NROI', 'PPSA'])) {
            echo json_encode(['success' => false, 'message' => 'Invalid role.']);
            exit;
        }
        $stmtUser = $pdo->prepare("SELECT id, first_name, last_name, nroi_id, area, status, role FROM users WHERE id = ? AND status = 'approved'");
        $stmtUser->execute([$id]);
        $userInfo = $stmtUser->fetch(PDO::FETCH_ASSOC);
        if (!$userInfo || $userInfo['area'] !== $officerArea) {
            echo json_encode(['success' => false, 'message' => 'You can only edit approved members in your area.']);
            exit;
        }

        // Enforce role boundaries for officers
        $targetUserRole = $userInfo['role'] ?? 'member';
        if ($is_ac) {
            $canHandle = in_array($targetUserRole, ['AAC', 'R.O', 'C.R.O', 'RO', 'CRO', 'member', '']);
            $allowedSettableRoles = ['R.O', 'C.R.O', 'AAC']; // AC can promote to AAC
        } else { // is_aac
            $canHandle = in_array($targetUserRole, ['R.O', 'C.R.O', 'RO', 'CRO', 'member', '']);
            $allowedSettableRoles = ['R.O', 'C.R.O'];
        }

        if (!$canHandle) {
            echo json_encode(['success' => false, 'message' => 'You do not have permission to manage this account type.']);
            exit;
        }

        if (!in_array($role, $allowedSettableRoles)) {
            echo json_encode(['success' => false, 'message' => 'Invalid role assignment for your session.']);
            exit;
        }

        $stmt = $pdo->prepare("UPDATE users SET role = ?, rank = ? WHERE id = ?");
        $stmt->execute([$role, $rank ?: null, $id]);
        $performedByRole = $is_ac ? 'AC' : 'AAC';
        $performedByUserId = $_SESSION['user_id'] ?? null;
        $description = "Updated member: " . ($userInfo['first_name'] ?? '') . " " . ($userInfo['last_name'] ?? '') . " (NROI ID: " . ($userInfo['nroi_id'] ?? 'N/A') . ") - Role: {$role}, Rank: " . ($rank ?: '—');
        logActivity($pdo, 'user', $id, $description, 'updated', $performedByRole, $performedByUserId, null);
        echo json_encode(['success' => true, 'message' => 'Member updated.']);

    } elseif ($action === 'update_profile') {
        // Only Admin can update user profiles
        if (!$is_admin) {
            echo json_encode(['success' => false, 'message' => 'Unauthorized: Only administrators can update user profiles']);
            exit;
        }
        // For general updates (Area/Role only)
        $role = $_POST['role'] ?? '';
        $area = $_POST['area'] ?? '';
        $rankInput = trim($_POST['rank'] ?? 'Regular');
        $rank = in_array(strtoupper($rankInput), ['REGULAR', 'OJT', 'INTERN']) ? (strtoupper($rankInput) === 'REGULAR' ? 'Regular' : strtoupper($rankInput)) : 'Regular';

        if (!in_array($role, ['R.O', 'C.R.O', 'AC', 'AAC', 'RM', 'NROI', 'PPSA'])) {
            throw new Exception("Invalid role selection");
        }

        // Get user info for logging
        $stmtUser = $pdo->prepare("SELECT first_name, last_name, nroi_id FROM users WHERE id = ?");
        $stmtUser->execute([$id]);
        $userInfo = $stmtUser->fetch(PDO::FETCH_ASSOC);

        $stmt = $pdo->prepare("UPDATE users SET role = ?, area = ?, rank = ? WHERE id = ?");
        $stmt->execute([$role, $area, $rank, $id]);

        // Log activity
        $performedByRole = 'ADMIN';
        $performedByAdminId = $_SESSION['admin_id'];
        $description = "Updated profile of user: " . ($userInfo['first_name'] ?? '') . " " . ($userInfo['last_name'] ?? '') . " (NROI ID: " . ($userInfo['nroi_id'] ?? 'N/A') . ") - Role: {$role}, Rank: {$rank}, Area: {$area}";
        logActivity($pdo, 'user', $id, $description, 'updated', $performedByRole, null, $performedByAdminId);

        echo json_encode(['success' => true, 'message' => 'User assignments updated.']);

    } elseif ($action === 'delete') {
        // Only Admin can delete users
        if (!$is_admin) {
            echo json_encode(['success' => false, 'message' => 'Unauthorized: Only administrators can delete users']);
            exit;
        }
        // Get user info for logging before deletion
        $stmtUser = $pdo->prepare("SELECT first_name, last_name, nroi_id FROM users WHERE id = ?");
        $stmtUser->execute([$id]);
        $userInfo = $stmtUser->fetch(PDO::FETCH_ASSOC);

        // Log permanent deletion
        $stmtLog = $pdo->prepare("INSERT INTO removed_accounts (user_id, removal_type, removed_by_admin_id) VALUES (?, 'permanent', ?)");
        $stmtLog->execute([$id, $_SESSION['admin_id']]);

        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
        $stmt->execute([$id]);

        // Log activity
        $performedByRole = 'ADMIN';
        $performedByAdminId = $_SESSION['admin_id'];
        $description = "Permanently deleted user account: " . ($userInfo['first_name'] ?? '') . " " . ($userInfo['last_name'] ?? '') . " (NROI ID: " . ($userInfo['nroi_id'] ?? 'N/A') . ")";
        logActivity($pdo, 'user', $id, $description, 'deleted', $performedByRole, null, $performedByAdminId);

        echo json_encode(['success' => true, 'message' => 'User deleted successfully']);

    } elseif ($action === 'remove_temp') {
        // Get user info for validation and logging
        $stmtUser = $pdo->prepare("SELECT first_name, last_name, nroi_id, area, role FROM users WHERE id = ?");
        $stmtUser->execute([$id]);
        $userInfo = $stmtUser->fetch(PDO::FETCH_ASSOC);

        if (!$userInfo) {
            echo json_encode(['success' => false, 'message' => 'User not found']);
            exit;
        }

        if (!$is_admin) {
            if (!$is_officer_role) {
                echo json_encode(['success' => false, 'message' => 'Unauthorized: Only administrators and officers can remove users']);
                exit;
            }

            $officerArea = trim($_SESSION['area'] ?? '');
            $userArea = trim($userInfo['area'] ?? '');
            if ($officerArea === '' || $userArea !== $officerArea) {
                echo json_encode(['success' => false, 'message' => 'You can only remove users in your area.']);
                exit;
            }

            // Enforce role boundaries for officers
            $targetUserRole = $userInfo['role'] ?? 'member';
            if ($is_ac) {
                $canHandle = in_array($targetUserRole, ['AAC', 'R.O', 'C.R.O', 'RO', 'CRO', 'member', '']);
            } else { // is_aac
                $canHandle = in_array($targetUserRole, ['R.O', 'C.R.O', 'RO', 'CRO', 'member', '']);
            }

            if (!$canHandle) {
                echo json_encode(['success' => false, 'message' => 'You do not have permission to remove this account type.']);
                exit;
            }
        }

        // Set user to deactivated and log in removed_accounts
        $stmt = $pdo->prepare("UPDATE users SET status = 'deactivated' WHERE id = ?");
        $stmt->execute([$id]);

        $removedByAdminId = $is_admin ? $_SESSION['admin_id'] : null;
        $removedByUserId = !$is_admin ? ($_SESSION['user_id'] ?? null) : null;
        $stmtLog = $pdo->prepare("INSERT INTO removed_accounts (user_id, removal_type, removed_by_admin_id, removed_by_user_id) VALUES (?, 'temporary', ?, ?)");
        $stmtLog->execute([$id, $removedByAdminId, $removedByUserId]);

        // Log activity
        $performedByRole = $is_admin ? 'ADMIN' : ($is_ac ? 'AC' : 'AAC');
        $performedByAdminId = $is_admin ? $_SESSION['admin_id'] : null;
        $performedByUserId = !$is_admin ? ($_SESSION['user_id'] ?? null) : null;

        $description = ($is_admin ? "Temporarily removed" : "Archived") . " user account: " . ($userInfo['first_name'] ?? '') . " " . ($userInfo['last_name'] ?? '') . " (NROI ID: " . ($userInfo['nroi_id'] ?? 'N/A') . ")";
        logActivity($pdo, 'user', $id, $description, 'removed', $performedByRole, $performedByUserId, $performedByAdminId);

        echo json_encode(['success' => true, 'message' => 'User ' . ($is_admin ? 'temporarily removed' : 'archived') . ' successfully.']);

    } elseif ($action === 'archive_restore') {
        if (!$is_admin) {
            echo json_encode(['success' => false, 'message' => 'Unauthorized: Only administrators can restore users']);
            exit;
        }
        $removedIds = explode(',', $_POST['removed_id'] ?? '');
        $userIds = explode(',', $_POST['user_id'] ?? '');
        $removedIds = array_filter($removedIds);
        $userIds = array_filter($userIds);

        if (empty($removedIds) || empty($userIds)) {
            echo json_encode(['success' => false, 'message' => 'Missing archived record or user IDs']);
            exit;
        }

        $pdo->beginTransaction();
        try {
            $stmtUser = $pdo->prepare("UPDATE users SET status = 'approved' WHERE id = ?");
            foreach ($userIds as $userId) {
                $stmtUser->execute([$userId]);
            }

            $stmtRemoved = $pdo->prepare("DELETE FROM removed_accounts WHERE id = ?");
            foreach ($removedIds as $removedId) {
                $stmtRemoved->execute([$removedId]);
            }
            $pdo->commit();
            echo json_encode(['success' => true, 'message' => 'User(s) restored successfully.']);
        } catch (Exception $e) {
            $pdo->rollBack();
            throw $e;
        }

    } elseif ($action === 'archive_permanent') {
        if (!$is_admin) {
            echo json_encode(['success' => false, 'message' => 'Unauthorized: Only administrators can permanently remove users']);
            exit;
        }
        $removedIds = explode(',', $_POST['removed_id'] ?? '');
        $userIds = explode(',', $_POST['user_id'] ?? '');
        $removedIds = array_filter($removedIds);
        $userIds = array_filter($userIds);

        if (empty($removedIds) || empty($userIds)) {
            echo json_encode(['success' => false, 'message' => 'Missing archived record or user IDs']);
            exit;
        }

        $pdo->beginTransaction();
        try {
            $stmtRemoved = $pdo->prepare("UPDATE removed_accounts SET removal_type = 'permanent' WHERE id = ?");
            foreach ($removedIds as $removedId) {
                $stmtRemoved->execute([$removedId]);
            }

            $stmtUser = $pdo->prepare("DELETE FROM users WHERE id = ?");
            foreach ($userIds as $userId) {
                $stmtUser->execute([$userId]);
            }
            $pdo->commit();
            echo json_encode(['success' => true, 'message' => 'User(s) permanently removed.']);
        } catch (Exception $e) {
            $pdo->rollBack();
            throw $e;
        }

    } elseif ($action === 'create_user') {
        // Admin and Officers (AC/AAC) can create users
        if (!$is_admin && !$is_officer_role) {
            echo json_encode(['success' => false, 'message' => 'Unauthorized: Only administrators and officers can create users']);
            exit;
        }
        // Collect inputs
        $firstName = $_POST['first_name'] ?? '';
        $lastName = $_POST['last_name'] ?? '';
        $middleName = $_POST['middle_name'] ?? '';
        $gender = $_POST['gender'] ?? '';
        $dob = $_POST['dob'] ?? '';
        $age = $_POST['age'] ?? 0;
        $nroiId = $_POST['nroi_id'] ?? '';
        $ppsaId = $_POST['ppsa_id'] ?? '';
        $email = $_POST['email'] ?? '';
        $phone = $_POST['phone_number'] ?? '';
        $password = $_POST['password'] ?? '';
        $role = $_POST['role'] ?? 'R.O';
        $area = $_POST['area'] ?? '';

        if (!$is_admin) {
            // Security: limit roles and area that officers can assign
            $allowedRoles = ['R.O', 'C.R.O'];
            if ($is_ac) {
                $allowedRoles[] = 'AAC';
            }
            if (!in_array($role, $allowedRoles)) {
                $role = 'R.O';
            }
            $area = $_SESSION['area'] ?? '';
            if (empty($area)) {
                throw new Exception("Unauthorized: Your area is not set.");
            }
        }

        if (empty($area) && $role !== 'RM') {
            throw new Exception("Area assignment is required");
        }

        // Validation
        if (empty($firstName) || empty($lastName) || empty($email) || empty($phone) || empty($password) || empty($nroiId)) {
            throw new Exception("Required fields are missing (including NROI ID)");
        }

        // Check duplicates
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ? OR phone_number = ? OR nroi_id = ?");
        $stmt->execute([$email, $phone, $nroiId]);
        if ($stmt->fetchColumn() > 0) {
            throw new Exception("Email, Phone Number, or NROI ID already exists in the system.");
        }

        if (!empty($ppsaId)) {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE ppsa_id = ?");
            $stmt->execute([$ppsaId]);
            if ($stmt->fetchColumn() > 0) {
                throw new Exception("PPSA ID already exists.");
            }
        }

        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

        $profilePhoto = '';
        if (isset($_FILES['profile_photo']) && $_FILES['profile_photo']['error'] === 0) {
            $targetDir = "../storage/user_profile/";
            if (!is_dir($targetDir)) {
                mkdir($targetDir, 0777, true);
            }
            $fileExtension = strtolower(pathinfo($_FILES["profile_photo"]["name"], PATHINFO_EXTENSION));
            $fileName = $nroiId . "_" . time() . "." . $fileExtension;
            $targetFile = $targetDir . $fileName;

            if (move_uploaded_file($_FILES["profile_photo"]["tmp_name"], $targetFile)) {
                $profilePhoto = "storage/user_profile/" . $fileName;
            } else {
                throw new Exception("Failed to upload profile photo.");
            }
        } else {
            throw new Exception("Profile photo is required.");
        }

        // Admin-created accounts are immediately approved; officer-created accounts go to pending
        $initialStatus = $is_admin ? 'approved' : 'pending';
        $rank = $_POST['rank'] ?? 'Regular';

        $sql = "INSERT INTO users (
            nroi_id, ppsa_id, role, profile_photo, status, rank,
            first_name, last_name, middle_name, gender, dob, age,
            region, province, city_municipality, barangay, zipcode, street,
            facebook_link, viber_number, telegram_number,
            emergency_contact_name, emergency_contact_number,
            email, phone_number, password, area, is_active_nroi_member
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $nroiId,
            $ppsaId,
            $role,
            $profilePhoto,
            $initialStatus,
            $rank,
            $firstName,
            $lastName,
            $middleName,
            $gender,
            $dob,
            $age,
            $_POST['region'] ?? '',
            $_POST['province'] ?? '',
            $_POST['city_municipality'] ?? '',
            $_POST['barangay'] ?? '',
            $_POST['zipcode'] ?? '',
            $_POST['street'] ?? '',
            $_POST['facebook_link'] ?? '',
            $_POST['viber_number'] ?? '',
            $_POST['telegram_number'] ?? '',
            $_POST['emergency_contact_name'] ?? '',
            $_POST['emergency_contact_number'] ?? '',
            $email,
            $phone,
            $hashedPassword,
            $area,
            (isset($_POST['is_active_nroi_member']) && $_POST['is_active_nroi_member'] === 'yes' ? 1 : 0)
        ]);

        $newUserId = $pdo->lastInsertId();

        // Log activity
        $performedByRole = $is_admin ? 'ADMIN' : ($is_ac ? 'AC' : ($is_aac ? 'AAC' : 'UNKNOWN'));
        $performedByAdminId = $is_admin ? $_SESSION['admin_id'] : null;
        $performedByUserId = !$is_admin ? ($_SESSION['user_id'] ?? null) : null;
        $description = "Created new user account: {$firstName} {$lastName} (NROI ID: {$nroiId}) - Role: {$role}, Area: {$area}, Status: {$initialStatus}";
        logActivity($pdo, 'user', $newUserId, $description, $initialStatus, $performedByRole, $performedByUserId, $performedByAdminId);

        $message = $is_admin
            ? 'Account created and approved successfully'
            : 'Account created successfully and sent for admin approval (Pending).';

        echo json_encode(['success' => true, 'message' => $message]);

    } else {
        throw new Exception("Invalid action");
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
