<?php
/**
 * App API: AC/AAC account management for approved members (deactivate / remove-temp).
 * POST JSON: user_id (officer), action=deactivate|remove, target_id (member's user id).
 * Mirrors the web admin_user_actions.php update_status and remove_temp actions.
 */
require_once __DIR__ . '/../config/cors.php';
require_once __DIR__ . '/../config/db.php';

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

$response = ['success' => false, 'message' => ''];

try {
    $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
    $officerUserId = isset($input['user_id']) ? (int) $input['user_id'] : 0;
    $action        = trim(strtolower($input['action'] ?? ''));
    $targetId      = isset($input['target_id']) ? (int) $input['target_id'] : 0;

    if ($officerUserId <= 0 || $targetId <= 0 || !in_array($action, ['deactivate', 'remove'])) {
        $response['message'] = 'Missing or invalid user_id, target_id, or action.';
        echo json_encode($response);
        exit;
    }

    // Verify officer
    $stmt = $pdo->prepare("SELECT id, role, area FROM users WHERE id = ? AND status = 'approved'");
    $stmt->execute([$officerUserId]);
    $officer = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$officer || !in_array($officer['role'], ['AC', 'AAC'])) {
        $response['message'] = 'Unauthorized. AC or AAC only.';
        echo json_encode($response);
        exit;
    }

    $officerArea = trim($officer['area'] ?? '');
    $officerRole = $officer['role'];

    // Verify target member
    $stmt = $pdo->prepare("SELECT id, first_name, last_name, nroi_id, area, role, status FROM users WHERE id = ?");
    $stmt->execute([$targetId]);
    $target = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$target) {
        $response['message'] = 'User not found.';
        echo json_encode($response);
        exit;
    }

    $targetArea = trim($target['area'] ?? '');
    if ($officerArea === '' || $targetArea !== $officerArea) {
        $response['message'] = 'You can only manage users in your area.';
        echo json_encode($response);
        exit;
    }

    // Role boundary check
    $targetRole = $target['role'] ?? '';
    if ($officerRole === 'AC') {
        $canHandle = in_array($targetRole, ['AAC', 'R.O', 'C.R.O', 'RO', 'CRO', 'member', '']);
    } else { // AAC
        $canHandle = in_array($targetRole, ['R.O', 'C.R.O', 'RO', 'CRO', 'member', '']);
    }
    if (!$canHandle) {
        $response['message'] = 'You do not have permission to manage this account type.';
        echo json_encode($response);
        exit;
    }

    // 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
        )
    ");

    // Ensure removed_accounts table exists
    $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
        )
    ");

    $fullName = trim(($target['first_name'] ?? '') . ' ' . ($target['last_name'] ?? ''));
    $nroiId   = $target['nroi_id'] ?? 'N/A';

    $logStmt = $pdo->prepare("
        INSERT INTO activity_logs (reference_type, reference_id, description, status, performed_by_role, performed_by_user_id, performed_by_admin_id)
        VALUES (?, ?, ?, ?, ?, ?, NULL)
    ");

    if ($action === 'deactivate') {
        // Toggle: if already deactivated, re-activate; otherwise deactivate
        $newStatus = ($target['status'] === 'deactivated') ? 'approved' : 'deactivated';
        $stmt = $pdo->prepare("UPDATE users SET status = ? WHERE id = ?");
        $stmt->execute([$newStatus, $targetId]);

        $actionLabel = $newStatus === 'deactivated' ? 'Deactivated' : 'Re-activated';
        $desc = "{$actionLabel} user account: {$fullName} (NROI ID: {$nroiId})";
        $logStmt->execute(['user', $targetId, $desc, $newStatus, $officerRole, $officerUserId]);

        $response['success']    = true;
        $response['new_status'] = $newStatus;
        $response['message']    = "Account {$actionLabel} successfully.";

    } elseif ($action === 'remove') {
        // Archive (temporary remove) – same as remove_temp on web
        $stmt = $pdo->prepare("UPDATE users SET status = 'deactivated' WHERE id = ?");
        $stmt->execute([$targetId]);

        $stmtLog = $pdo->prepare("INSERT INTO removed_accounts (user_id, removal_type, removed_by_admin_id, removed_by_user_id) VALUES (?, 'temporary', NULL, ?)");
        $stmtLog->execute([$targetId, $officerUserId]);

        $desc = "Archived user account: {$fullName} (NROI ID: {$nroiId})";
        $logStmt->execute(['user', $targetId, $desc, 'removed', $officerRole, $officerUserId]);

        $response['success'] = true;
        $response['message'] = 'User archived successfully.';
    }

} catch (Throwable $e) {
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
