<?php
declare(strict_types=1);

/**
 * /public_html/test_erp/api/auth/delete_user.php
 *
 * Secure User Deactivation Endpoint — TEST Environment
 *
 * User স্থায়ীভাবে Delete করা হবে না।
 * শুধু status = inactive করা হবে।
 */

require_once __DIR__ . '/../../config/session.php';
require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../_csrf_guard.php';

header('Content-Type: application/json; charset=UTF-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

/**
 * Consistent JSON response.
 */
function delete_user_response(
    int $httpCode,
    bool $success,
    string $message,
    ?array $data = null
): void {
    http_response_code($httpCode);

    echo json_encode([
        'status'  => $success,
        'success' => $success,
        'ok'      => $success,
        'code'    => $httpCode,
        'message' => $message,
        'data'    => $data,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    exit;
}

/**
 * Audit failure হলেও User deactivation বন্ধ হবে না।
 */
function delete_user_audit(
    PDO $pdo,
    int $recordId,
    int $changedBy,
    string $note
): void {
    try {
        $ipAddress = (string) ($_SERVER['REMOTE_ADDR'] ?? '');

        $stmt = $pdo->prepare(
            "INSERT INTO audit_log
                (
                    table_name,
                    record_id,
                    action,
                    changed_by,
                    changed_at,
                    ip_address,
                    note
                )
             VALUES
                (
                    'users',
                    ?,
                    'UPDATE',
                    ?,
                    NOW(),
                    ?,
                    ?
                )"
        );

        $stmt->execute([
            $recordId,
            $changedBy,
            $ipAddress,
            $note,
        ]);

    } catch (Throwable $exception) {
        // Audit error হলেও মূল কাজ বন্ধ হবে না।
    }
}

/*
|--------------------------------------------------------------------------
| Request Method
|--------------------------------------------------------------------------
*/

$requestMethod = strtoupper(
    (string) ($_SERVER['REQUEST_METHOD'] ?? '')
);

if ($requestMethod === 'OPTIONS') {
    http_response_code(204);
    exit;
}

if ($requestMethod !== 'POST') {
    delete_user_response(
        405,
        false,
        'শুধু POST অনুরোধ গ্রহণযোগ্য'
    );
}

/*
|--------------------------------------------------------------------------
| Login Verification
|--------------------------------------------------------------------------
*/

$currentUserId = (int) ($_SESSION['user_id'] ?? 0);

if ($currentUserId <= 0) {
    delete_user_response(
        401,
        false,
        'প্রথমে লগইন করুন'
    );
}

$currentRole = strtolower(
    trim(
        (string) (
            $_SESSION['user_role']
            ?? $_SESSION['role']
            ?? ''
        )
    )
);

if (!in_array($currentRole, ['admin', 'manager'], true)) {
    delete_user_response(
        403,
        false,
        'ইউজার বন্ধ করার অনুমতি নেই'
    );
}

/*
|--------------------------------------------------------------------------
| CSRF Verification
|--------------------------------------------------------------------------
*/

erp_csrf_required(true);

/*
|--------------------------------------------------------------------------
| Database Verification
|--------------------------------------------------------------------------
*/

if (!isset($pdo) || !($pdo instanceof PDO)) {
    delete_user_response(
        500,
        false,
        'ডাটাবেস সংযোগ পাওয়া যায়নি'
    );
}

/*
|--------------------------------------------------------------------------
| Input গ্রহণ
|--------------------------------------------------------------------------
*/

$rawInput = file_get_contents('php://input');
$jsonInput = json_decode((string) $rawInput, true);

if (!is_array($jsonInput)) {
    $jsonInput = [];
}

$input = array_merge($_POST, $jsonInput);

$targetUserId = (int) ($input['id'] ?? 0);

if ($targetUserId <= 0) {
    delete_user_response(
        422,
        false,
        'User ID পাওয়া যায়নি'
    );
}

/*
|--------------------------------------------------------------------------
| নিজের Account বন্ধ করা যাবে না
|--------------------------------------------------------------------------
*/

if ($targetUserId === $currentUserId) {
    delete_user_response(
        403,
        false,
        'নিজের account বন্ধ করা যাবে না'
    );
}

/*
|--------------------------------------------------------------------------
| Target User যাচাই এবং Inactive করা
|--------------------------------------------------------------------------
*/

try {
    $pdo->beginTransaction();

    $targetStmt = $pdo->prepare(
        "SELECT
            id,
            name,
            email,
            role,
            status
         FROM users
         WHERE id = ?
         LIMIT 1
         FOR UPDATE"
    );

    $targetStmt->execute([$targetUserId]);

    $targetUser = $targetStmt->fetch(PDO::FETCH_ASSOC);

    if (!$targetUser) {
        $pdo->rollBack();

        delete_user_response(
            404,
            false,
            'ইউজার পাওয়া যায়নি'
        );
    }

    $targetRole = strtolower(
        trim((string) ($targetUser['role'] ?? ''))
    );

    $targetStatus = strtolower(
        trim((string) ($targetUser['status'] ?? ''))
    );

    /*
    |--------------------------------------------------------------------------
    | Permission Protection
    |--------------------------------------------------------------------------
    */

    /*
     * Manager শুধু Staff account বন্ধ করতে পারবে।
     */
    if (
        $currentRole === 'manager'
        && $targetRole !== 'staff'
    ) {
        $pdo->rollBack();

        delete_user_response(
            403,
            false,
            'Manager account থেকে শুধু Staff user বন্ধ করা যাবে'
        );
    }

    /*
     * সর্বশেষ Active Admin বন্ধ করা যাবে না।
     */
    if (
        $currentRole === 'admin'
        && $targetRole === 'admin'
        && $targetStatus === 'active'
    ) {
        $adminCountStmt = $pdo->query(
            "SELECT COUNT(*)
             FROM users
             WHERE role = 'admin'
               AND status = 'active'"
        );

        $activeAdminCount = (int) $adminCountStmt->fetchColumn();

        if ($activeAdminCount <= 1) {
            $pdo->rollBack();

            delete_user_response(
                403,
                false,
                'সর্বশেষ Active Admin account বন্ধ করা যাবে না'
            );
        }
    }

    /*
     * আগে থেকেই Inactive হলে আবার Update প্রয়োজন নেই।
     */
    if ($targetStatus === 'inactive') {
        $pdo->commit();

        delete_user_response(
            200,
            true,
            'ইউজার আগে থেকেই বন্ধ আছে',
            [
                'id'     => $targetUserId,
                'name'   => (string) $targetUser['name'],
                'role'   => $targetRole,
                'status' => 'inactive',
            ]
        );
    }

    $updateStmt = $pdo->prepare(
        "UPDATE users
         SET
            status = 'inactive',
            failed_login_attempts = 0,
            locked_until = NULL
         WHERE id = ?"
    );

    $updateStmt->execute([$targetUserId]);

    $pdo->commit();

    delete_user_audit(
        $pdo,
        $targetUserId,
        $currentUserId,
        'User deactivated — role: '
        . $targetRole
        . ' — TEST environment'
    );

    delete_user_response(
        200,
        true,
        'ইউজার বন্ধ করা হয়েছে',
        [
            'id'     => $targetUserId,
            'name'   => (string) $targetUser['name'],
            'role'   => $targetRole,
            'status' => 'inactive',
        ]
    );

} catch (PDOException $exception) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    delete_user_response(
        500,
        false,
        'সার্ভার সমস্যা হয়েছে, আবার চেষ্টা করুন'
    );

} catch (Throwable $exception) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    delete_user_response(
        500,
        false,
        'সার্ভার সমস্যা হয়েছে, আবার চেষ্টা করুন'
    );
}